Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/nameparser/_pipeline/_vocab.py: 21%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

886 statements  

1"""Shared vocabulary predicates for pipeline stages. 

2 

3Text-level tests used by more than one stage; piece-level ones live 

4in _pieces, the sibling layer over tokens-plus-tags. All take 

5normalized-or-raw text explicitly and no state, with the departures 

6named below. 

7 

8is_wholly_suffix departs from that shape twice, deliberately. It is 

9RUN-level rather than text-level, because the question it answers is 

10genuinely about a run: the Ph./D. merge spans two tokens, so no 

11per-token predicate composed with all() can express it. And it takes 

12the Policy OBJECT, where delimiter_cores takes a pre-extracted 

13frozenset so its caller hands in one field rather than the config -- 

14is_wholly_suffix needs TWO policy fields (lenient_comma_suffixes and 

15extra_suffix_delimiters), and threading both past every caller costs 

16more than the config parameter saves. Still no state: Policy is frozen 

17config, not pipeline state. 

18 

19maiden_marker_run is run-level for the first of those reasons and not 

20the second: a maiden marker may be a PHRASE ('z domu'), so how far one 

21reaches is a question about a run of words that no per-word membership 

22test can answer, and the vocabulary reaches it as a plain frozenset 

23field like every other predicate here. 

24 

25tag_marker_runs is the third departure, and the reason this module also 

26imports _state (WorkToken, comma_bucket): deciding which tokens open a 

27maiden-marker RUN needs each token's role and span, not its text alone, 

28because a run must not cross a role change or a comma. It moved here 

29from classify (#289/#516) so _pieces.own_words -- which may import 

30only _state and _vocab (tests/v2/test_layering.py) -- can call the 

31SAME function classify does rather than approximating it with a 

32text-only walk. Two callers building a map from the same tokens with 

33the same function cannot disagree, which a from-scratch approximation 

34could (measured: 'ANNA z Nowak, MD' flips the one-case verdict when 

35the approximation and the real run-completion test disagree on 

36whether 'z' opens a run that completes). 

37 

38suffix_reading, name_reading and the two reading constants are the 

39fourth: they answer no question about a word but BUILD the reading a 

40report did not take (#752 phase 2m), from a token's text and tags, 

41which is why they import _state's PendingReading and the public enums 

42it re-exports. They sit here because every stage that reports a fork 

43builds one, and the tags they read are this module's vocabulary. 

44 

45Layering: imports _lexicon, _policy, and _pipeline._state (WorkToken, 

46comma_bucket, PendingReading -- read-only, never a whole ParseState). 

47""" 

48from __future__ import annotations 

49 

50import functools 

51import re 

52import string 

53import unicodedata 

54from collections.abc import Callable, Iterable, Sequence, Set 

55from typing import Literal 

56 

57from nameparser._lexicon import ( 

58 FULL_STOPS, Lexicon, _HYPHEN_CHARS, _VOCAB_FIELDS, _normalize, 

59 _spells_an_initial, 

60) 

61from nameparser._policy import ( 

62 CapsSuffixes, Policy, Script, _CASELESS_LETTERS, _EAST_ASIAN_SCRIPTS, 

63 _JA_SCRIPTS, _NO_ABBREVIATION_RANGES, _NO_INITIAL_RANGES, _SCRIPT_RANGES, 

64 _SPELLED_INITIAL_RANGES, _ranges_matcher, _ranges_pattern, _script_matcher, 

65) 

66from nameparser._pipeline._state import ( 

67 AGNOMEN_TAG, AMBIGUOUS_ACRONYM_TAG, AMBIGUOUS_WORD_TAG, CAPITALS_FAMILY_TAG, 

68 COMMA_CHARS, COMMA_STRIP, 

69 CREDENTIAL_WORD_TAG, Deferred, GENERATION_WORD_TAG, 

70 GIVEN_ABBREVIATION_TAG, HONORIFIC_WORD_TAG, PATRONYMIC_TAG, SHAPE_ACRONYM_TAG, 

71 TITLE_AMBIGUOUS_TAG, PendingReading, ReadingKind, ReadingSource, Role, WorkToken, 

72 comma_bucket, 

73) 

74 

75# Ported verbatim from v1's "initial" pattern (the 1.x and 2.x 

76# nameparser.config.regexes, removed in 3.0, #1008) minus its 

77# empty-string alternative -- WorkToken text is never empty. _render 

78# holds a hand copy, pinned to this one by tests/v2/test_regex_sync.py. 

79# "Verbatim" is a promise about the PATTERN, not about the predicate: 

80# since #320 is_initial is this SHAPE test ANDed with a repertoire test 

81# (in_initialless_script, below), so _INITIAL.fullmatch(text) and 

82# is_initial(text) are no longer the same question -- '씨.' answers yes 

83# to the first and no to the second. Call is_initial; the bare pattern 

84# is not the thing to ask. The narrowing lives in the predicate 

85# precisely so this copy can stay exactly as verbatim as it ever was, 

86# the pattern _render's copy must equal. 

87_INITIAL = re.compile(r"^(\w\.|[A-Z])$") 

88 

89# Ported verbatim from v1's "period_not_at_end" pattern (the 1.x and 

90# 2.x nameparser.config.regexes, removed in 3.0, #1008). 

91_PERIOD_NOT_AT_END = re.compile(r".*\..+$", re.I) 

92 

93# The fix_phd credential pair ('Ph.' + 'D.' as adjacent tokens), 

94# `split_pair`'s first answer, below. 

95_PH = re.compile(r"^ph\.?$", re.IGNORECASE) 

96_D = re.compile(r"^d\.?$", re.IGNORECASE) 

97#: `split_pair`'s necessary half on its FIRST word for the Ph./D. 

98#: answer alone, asked C-level by `is_wholly_suffix` ahead of the 

99#: call, the one caller that asks only that answer and has no tags to 

100#: read. The same compiled object the predicate asks, so the two 

101#: cannot drift. 

102SPLIT_PAIR_OPENS = _PH 

103 

104 

105# The codepoint table lives in _policy beside Script -- one copy 

106# importable from the pipeline and the locale packs alike; everything 

107# here DERIVES from it. (A compiled class, not a per-character range 

108# test: decisions/parse-cost, 2026-07-28 a102c868, holds the 

109# measurement.) 

110# Derived, never hand-written -- even the class construction goes 

111# through the shared factory: one wholly-of predicate per script, in 

112# the table's key order -- the FIRST-covering-entry rule _classify 

113# documents. 

114_SCRIPT_MATCHERS: dict[Script, Callable[[str], bool]] = { 

115 script: _script_matcher(script, whole=True) 

116 for script in _SCRIPT_RANGES 

117} 

118#: The East Asian matchers _classify tries in turn, and the characters a 

119#: Cyrillic word can open with: a token opening with none of them is no 

120#: Cyrillic, which a C-level membership test says without the matcher's 

121#: frame, so a non-ASCII Latin word pays nothing for Cyrillic (#1237) 

122_EAST_ASIAN_MATCHERS = tuple((script, _SCRIPT_MATCHERS[script]) 

123 for script in _EAST_ASIAN_SCRIPTS) 

124_CYRILLIC_LETTERS = frozenset(chr(c) for lo, hi in _SCRIPT_RANGES[Script.CYRILLIC] 

125 for c in range(lo, hi + 1)) 

126 

127#: The joiners a name word is written with inside it: hyphens and the 

128#: apostrophes a surname writes (`O'BRIEN`, `ALLIOT-MARIE`) and 

129#: Ukrainian and Belarusian write (`Оюун-Эрдэнэ`, `Мар'яна`). Read by 

130#: rules/O9's capitals word (`is_capitals_word`) and by the Cyrillic 

131#: order key, which deletes them from the classified copy of a word that 

132#: neither opens nor ends with one, so a hyphenated Cyrillic word keys a 

133#: declared Cyrillic order as a plain one does (#1237); the shared table 

134#: stays letters only, since the East Asian readers of it never see 

135#: these. 

136_NAME_JOINERS = "-\u2010\u2011'\u2019\u02bc" 

137_DROP_NAME_JOINERS = str.maketrans("", "", _NAME_JOINERS) 

138 

139# The whole-token matcher over _policy's _JA_SCRIPTS union, backing 

140# effective_script's kana license. 

141_wholly_ja = _script_matcher(*_JA_SCRIPTS, whole=True) 

142 

143# The four kana voicing marks U+3099-U+309C (#596). None belongs to 

144# either syllabary -- each voices the kana it follows -- but the script 

145# table classifies by block and all four sit in the HIRAGANA one, so a 

146# mark NFC cannot compose (ア + U+3099) made a katakana token read as 

147# katakana plus hiragana and took the kana license. 

148# _normalized_for_script drops every mark standing after a KANA, so the 

149# mark takes its base's script. After anything else -- hangul, Han, 

150# Latin, or nothing at all -- the mark is not voicing a kana and keeps 

151# the table's answer: deleting it there would hand 김゙민준 a script the 

152# surname site then divides on the RAW text, cutting the mark off its 

153# base and leaving it to open the given name. 

154_VOICING_MARKS = frozenset("\u3099\u309a\u309b\u309c") 

155 

156# Whole-text kana test for one character: the base a voicing mark may 

157# be dropped after. 

158_is_kana = _script_matcher(Script.HIRAGANA, Script.KATAKANA, whole=True) 

159 

160 

161def _drop_kana_voicing_marks(text: str) -> str: 

162 """`text` without the voicing marks that follow a kana (a run of 

163 them included); every other mark kept. Called only on text holding 

164 a mark, so names without one never pay for the walk.""" 

165 kept: list[str] = [] 

166 after_kana = False 

167 for ch in text: 

168 if ch in _VOICING_MARKS: 

169 if after_kana: 

170 continue 

171 else: 

172 after_kana = _is_kana(ch) 

173 kept.append(ch) 

174 return "".join(kept) 

175 

176# The repertoire half of is_initial (_policy._SCRIPT_PROPERTIES' 

177# writes_initials), kept apart 

178# from _INITIAL's SHAPE half so the pattern itself stays v1-verbatim 

179# and _render's copy stays pinned to it by tests/v2/test_regex_sync.py. 

180# contains-any, not whole=True: the shape half has already admitted the 

181# trailing period, so the text reaching here is '씨.' rather than '씨' 

182# and a wholly-of match would be False for every case this exists for. 

183_has_initialless_char = _ranges_matcher(_NO_INITIAL_RANGES, whole=False) 

184# The period-abbreviation repertoire veto (_SCRIPT_PROPERTIES' 

185# period_abbreviations), read through in_unabbreviating_script by H2's 

186# shape (is_title_shaped and _pieces.is_leading_title), S3's split 

187# pair (split_pair) and S3's joined shape (period_joined_vocab). 

188# is_title_shaped admits two or more 

189# characters, so contains-any there means one CJK character anywhere 

190# vetoes the whole word -- 'Kim김.' is refused as a title along with 

191# '田中.' -- and that is deliberate: a word carrying a script with no 

192# abbreviations is not wearing an abbreviation's period. 

193_has_unabbreviating_char = _ranges_matcher(_NO_ABBREVIATION_RANGES, 

194 whole=False) 

195 

196 

197def in_initialless_script(text: str) -> bool: 

198 """Whether TEXT holds a character of a script that writes no 

199 initials (#320), asked of the composed spelling, the one every 

200 shape test beside it reads, so the veto and the shape read one 

201 spelling (decisions/nfd-shapes, #665, #1087). ASCII answers without the 

202 matcher's frame, as the callers' own `isascii()` gates do.""" 

203 return (not text.isascii() 

204 and _has_initialless_char(unicodedata.normalize("NFC", text))) 

205 

206 

207def in_unabbreviating_script(text: str) -> bool: 

208 """Whether TEXT holds a character of a script that writes no period 

209 abbreviation (rules/H2, #323; rules/S3's split and joined shapes), 

210 asked of the composed spelling as 

211 `in_initialless_script` is, the two being separate questions that 

212 the four East Asian rows answer alike (#1256).""" 

213 return (not text.isascii() 

214 and _has_unabbreviating_char(unicodedata.normalize("NFC", text))) 

215 

216 

217# H2's own shape, text-level: an unlisted period-marked abbreviation, 

218# two or more letters, one trailing period. Moved here from _pieces 

219# (#289/#516, quality-review finding) so _vocab.name_word_count can 

220# ask the SAME question _pieces.is_leading_title asks -- measured 

221# divergence before the move: 'Dr. Smith, Ed' (LISTED title 'Dr.') and 

222# 'Xyz. Smith, Ed' (UNLISTED, H2-shaped) both read family 'Dr. 

223# Smith'/'Xyz. Smith', given 'Ed' at the peel (since #701 the listed 

224# 'Dr.' then peels into the title, rules/H6), because is_leading_title 

225# reads H2's shape and a bare `folded in lexicon._sets.titles` lookup does 

226# not -- but name_word_count's OWN count disagreed: 'Xyz.' counted as 

227# a name word where 'Dr.' did not, so 'Xyz. Smith, Ed' alone flipped 

228# the comma structure to a credential run 

229# (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

230# 

231# v1's "period_abbreviation" shape, composed from `_LETTER` below, so 

232# the text is v1's plus the marks. This is the only definition: 

233# `_pieces._PERIOD_ABBREV` is an import of it, which 

234# tests/v2/test_regex_sync.py declares as such. 

235 

236# `_LETTER` is the letter every shape regex in this module spells 

237# (`_PERIOD_ABBREV`, `_DOTTED`, `_CHUNKED`, `_PAIRED_INITIALS`): one 

238# letter (a word character that is not a digit or underscore) plus the 

239# combining marks written after it (#652). `inž.` typed as i, n, z, 

240# U+030C, '.' is the same word as the composed one, and `\w` alone ends 

241# it at the z. `_MARKS` is the general combining blocks -- what NFD of 

242# a Latin, Greek or Cyrillic letter produces -- and not the marks that 

243# only some scripts write (Indic vowel signs, Arabic and Hebrew 

244# points); rules/H2's Accepted bullet "The shape is only recognizable 

245# as an unbroken run of letters" owns that limit (decisions/H2). 

246_MARKS = '[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]' 

247_LETTER = r'[^\W\d_]' + _MARKS + '*' 

248_PERIOD_ABBREV = re.compile(r'^(?:' + _LETTER + r'){2,}\.$') 

249 

250# rules/H2: "A word in one of the ten Brahmic scripts from Devanagari 

251# to Sinhala" "never reads as a title by shape, even where it is a run 

252# of letters" -- the rows of _policy._SCRIPT_PROPERTIES whose 

253# spells_initials holds, U+0900 to U+0DFF. A vowel sign 

254# already breaks `_LETTER`'s run, but a spelled initial written with 

255# none (एम. for M., এম., ਐਮ.) is a run of two letters, and the shape 

256# read it as a title; these scripts write initials, so the veto is the 

257# title shape's alone and not `is_initial`'s (decisions/H2, #1191). 

258# Searched on the raw text: a nukta letter decomposes inside the range. 

259_SPELLED_INITIAL = _ranges_pattern(_SPELLED_INITIAL_RANGES) 

260 

261# rules/H2: "A transliteration digraph" "never reads as a title by 

262# shape" -- the digraphs that Except names, lowercase and periodless, 

263# so the test is a C-level membership of the word less its period; 

264# the Except itself names the digraphs it leaves out (Ts, Ch, Sh) -- 

265# decisions/H2 (#1136). 

266_DIGRAPH_INITIALS = frozenset({"yu", "ya", "ye", "yo", "zh", "kh", 

267 "shch", "dzh"}) 

268 

269#: `_lexicon._HYPHEN_CHARS`, defined once there, matched as a class: 

270#: the hyphens and the dashes that join two family names in one written 

271#: word (rules/O6), and the parts of an abbreviation written hyphenated 

272#: (rules/H5, 'Dipl.‐Ing.' as a word processor writes it): hyphen-minus, 

273#: hyphen, non-breaking hyphen, figure dash, en dash, minus sign (a word 

274#: processor's substitute), and the small and fullwidth hyphen-minus. 

275#: The em dashes are punctuation between words, not joiners, and are 

276#: left out. Hyphen-minus first, so it is literal inside a class. 

277_HYPHENS = re.compile("[" + _HYPHEN_CHARS + "]") 

278 

279# rules/H5: "A word that ends in a period and is written with a 

280# period or a hyphen inside it wears the abbreviation shape too" -- 

281# the trailing chain's shape, _PERIOD_ABBREV widened to 'Priv.-Doz.', 

282# 'Dipl.Ing.' and 'Lt.Col.'. It opens and closes on a letter and ends 

283# in one period, so every _PERIOD_ABBREV match is one of its matches; 

284# the front slot's H2 shape stays _PERIOD_ABBREV (decisions/H5, #1116). 

285_TRAILING_TITLE_SHAPE = re.compile( 

286 r'^' + _LETTER + r'(?:' + _LETTER + r'|[' + _HYPHEN_CHARS + r'.])*' 

287 + _LETTER + r'\.$') 

288 

289# rules/H5: "a title the vocabulary lists whole with a period inside 

290# it chains without a final one" -- the letters of such a listing 

291# joined by periods and hyphens ('dott.ssa', 'priv.-doz'), read by 

292# classify on the normalized word, which has no edge periods, ANDed 

293# there with a period test, since the pattern alone admits a word a 

294# hyphen alone joins ('co-founder'); a digit keeps a rank written with 

295# a period (a caller's 'cwo.3') out (decisions/H5, #1104). 

296_JOINED_WORD = re.compile( 

297 r'^(?:' + _LETTER + r')+(?:[' + _HYPHEN_CHARS + r'.]+(?:' 

298 + _LETTER + r')+)+$') 

299 

300 

301# rules/H2: "an abbreviation opening the part of the name that 

302# carries the given name — the whole name, or the part after a 

303# family comma — reads as a title even when unlisted" 

304# (history: decisions/H2) 

305def is_title_shaped(text: str, lexicon: Lexicon) -> bool: 

306 """Whether TEXT reads as a title by H2's shape -- the LISTED half 

307 being a separate lookup at each caller's own site 

308 (is_title_piece/lexicon._sets.titles), and the one vocabulary read here 

309 the given name written short, which outranks the shape (rules/H2, 

310 #789: 'Chas.' is no title). `name_word_count`, `title_readings` 

311 (classify's rules/H9 phrase test) and `_assemble`'s source of a 

312 title no vocabulary tags are its callers; `_pieces.is_leading_title` 

313 asks the same question but keeps this body inline, its path being 

314 hot (every leading piece of every parse) where these run only on a 

315 comma name, a name holding a contested title or modifier, or an 

316 untagged title token 

317 -- the measured figure lives at that inline copy and is not 

318 restated here, two homes for one measurement being how they come 

319 to disagree. Touch one, touch both: 

320 `test_pieces.test_is_title_shaped_and_is_leading_title_agree` 

321 runs both over the union of the two example tables, so the 

322 agreement is checked rather than asserted in prose 

323 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

324 

325 The shape reads a Latin convention: a period marks an 

326 abbreviation, and a script that writes no period abbreviations 

327 (_policy._SCRIPT_PROPERTIES' period_abbreviations) has nothing for 

328 one to mark, so a CJK word wearing a period is a name word, not a 

329 title -- a lone '田中.' is the family name (#323). The four East 

330 Asian rows write no initials either; Thai writes no initials but 

331 writes its titles short, so the two are separate columns (#1256). 

332 `_PERIOD_ABBREV` stays ASCII-period only: a word wearing '。' never 

333 matches it, and the veto is what makes the ASCII spelling agree. 

334 ASCII text can carry no such character (every range sits 

335 above U+007F), so the C-level test declines before the regex 

336 search runs -- four frames per unlisted-abbreviation opener per 

337 parse, this running four times per piece. 

338 

339 A word holding a letter of the ten Brahmic scripts from Devanagari 

340 to Sinhala is refused too (`_SPELLED_INITIAL`, rules/H2's Except, 

341 #1191): those scripts write initials, and spell a Latin one out by 

342 its sound with no vowel sign (एम. for M.), a run of letters the 

343 shape would misread. Its search is C-level, so it costs no frame. 

344 

345 A transliteration digraph (`Yu.`, `Zh.`, `Kh.`, `_DIGRAPH_INITIALS`) 

346 declines the shape too, being the initial of one Cyrillic letter 

347 (rules/H2's transliteration-digraph Except, #1136). 

348 """ 

349 return (bool(_PERIOD_ABBREV.match(text)) 

350 and (text.isascii() or not (_SPELLED_INITIAL.search(text) 

351 or in_unabbreviating_script(text))) 

352 and text[:-1].lower() not in _DIGRAPH_INITIALS 

353 and _normalize(text) not in lexicon._sets.given_name_abbreviations) 

354 

355 

356def is_initial_shaped(text: str) -> bool: 

357 """v1's is_an_initial verbatim: the SHAPE half alone -- one word 

358 character plus a period, or a bare ASCII capital. 

359 

360 Callers asking whether a token is STRUCTURALLY part of an initial 

361 run want this; callers asking whether it can really stand in for a 

362 name want is_initial (#320). The two answers differ only inside 

363 scripts that write no initials, where '씨.' is initial-SHAPED but is not an 

364 initial -- see assign's roman-numeral fork, the shape caller, for 

365 what picking the wrong one costs. 

366 

367 Asked of the composed spelling, as `_render` asks it (#542): `\\w` 

368 does not match a combining mark, so a decomposed 'É.' is three 

369 characters to the pattern and no initial (#665). Composing rather 

370 than widening keeps the pattern v1-verbatim, and both calls are 

371 C-level, so the predicate costs no frame it did not before.""" 

372 if not text.isascii(): 

373 text = unicodedata.normalize("NFC", text) 

374 return bool(_INITIAL.fullmatch(text)) 

375 

376 

377# v1's "roman_numeral" pattern; _render's hand copy is pinned to this 

378# one by tests/v2/test_regex_sync.py. 

379_ROMAN = re.compile(r'^(X|IX|IV|V?I{0,3})$', re.I) 

380#: The same pattern, shared rather than copied: `_comma` filters on 

381#: it before asking `reads_as_generation` (rules/C12). 

382ROMAN = _ROMAN 

383 

384 

385# Ported from v1's patterns (the 1.x and 2.x 

386# nameparser.config.regexes, removed in 3.0, #1008), the RU and TR_AZ 

387# packs' copies pinned to these by tests/v2/test_locales.py: the East 

388# Slavic patronymic endings and the standalone Turkic patronymic 

389# markers, which rules/O1's and O2's rotations, rules/R9's reading and 

390# the group suggester's patronymic signal (nameparser/_suggest.py) ask 

391# through the two predicates below. The Ukrainian Cyrillic endings are 

392# decisions/O1's (#1212). 

393_EAST_SLAVIC = re.compile( 

394 r"(ovich|ovna|evich|evna|ichna|ilyich|kuzmich|lukich|fomich|fokich|nikitich|savvich)$", 

395 re.I) 

396_EAST_SLAVIC_CYR = re.compile( 

397 r"(ович|овна|евич|евна|ична|ильич|івна|ївна|євич|ілліч" 

398 r"|кузьмич|лукич|фомич|фокич|никитич|саввич)$", 

399 re.I) 

400_TURKIC = re.compile( 

401 r"^(oglu|oğlu|ogly|ogli|o['’ʻ‘ʼ`]g['’ʻ‘ʼ`]li" 

402 r"|qizi|qızı|kizi|kyzy|gyzy|uly|uulu)$", re.I) 

403_TURKIC_CYR = re.compile( 

404 r"^(оглу|оглы|оғлу|ўғли|угли|кызы|гызы|қызы|қизи|улы|ұлы|уулу)$", re.I) 

405 

406 

407def has_patronymic_ending(text: str) -> bool: 

408 """Whether `text` ends in an East Slavic patronymic ending, Latin or 

409 Cyrillic ("Ivanovich", "Петрович"): rules/O1's test and, under 

410 `PatronymicRule.EAST_SLAVIC`, rules/R9's. Asked of the word 

411 NFC-composed, as `is_patronymic_marker` is (#1316): the Ukrainian 

412 `ї` of `-ївна` decomposes to і and a combining diaeresis (#1212); 

413 the fold is inline behind `isascii()` so a plain word costs no 

414 frame.""" 

415 if not text.isascii(): 

416 text = unicodedata.normalize("NFC", text) 

417 return bool(_EAST_SLAVIC.search(text) or _EAST_SLAVIC_CYR.search(text)) 

418 

419 

420def is_patronymic_marker(text: str) -> bool: 

421 """Whether `text` is a standalone Turkic patronymic marker ("oglu", 

422 "кызы"): rules/O2's test and, under `PatronymicRule.TURKIC`, 

423 rules/R9's. Asked of the word NFC-composed (#1316): `oğlu` written 

424 with a combining breve is the same marker, the vocabulary path's fold 

425 applied to a shape test; the fold is inline behind `isascii()` so a 

426 plain word costs no frame.""" 

427 if not text.isascii(): 

428 text = unicodedata.normalize("NFC", text) 

429 return bool(_TURKIC.match(text) or _TURKIC_CYR.match(text)) 

430 

431 

432# rules/O1: "whose last name word carries a patronymic ending and whose 

433# middle name word does not reads as family-first" -- the word test of 

434# the rotation, shared with the group suggester (nameparser/_suggest.py), 

435# which counts a patronymic vote where this rule can read one 

436# (decisions/group-suggestion) 

437def east_slavic_rotates(middle: str, last: str) -> bool: 

438 """Whether the middle and last of three name words have rules/O1's 

439 family-first shape: the ending on the last word and not on the 

440 middle one. The word count and the initials beside it are the 

441 caller's.""" 

442 return has_patronymic_ending(last) and not has_patronymic_ending(middle) 

443 

444 

445# rules/S10: "the numeral reads as the generation: the numerals the 

446# vocabulary lists, and those up to X it does not, by their shape 

447# alone" -- its Then clause, the `_ROMAN` test; and rules/S10's Except 

448# bullet "An initial in front makes it a name word too", the two 

449# is_initial_shaped tests on `preceding`. The words-to-spare count, 

450# rules/S10's Except bullet "A numeral of one letter needs words to 

451# spare", is the callers'. decisions/S10 (#718, #721) 

452# mechanisms.md#ONE-PREDICATE-PER-QUESTION ("exactly one predicate answers it and every other site calls that one") 

453# -- the numeral's predicate, which every numeral rule asks 

454# (decisions/vocabulary-model, #752; #784, #774, #819) 

455def reads_as_generation(text: str, tags: Set[str], preceding: str | None, 

456 one_case: bool | None) -> bool: 

457 """Whether a word reads as the generation: S10's roman-numeral 

458 fork, asked by every rule that weighs a numeral (#752). For a 

459 one-letter numeral a necessary condition only: the words-to-spare 

460 count is the caller's, which alone knows where the name's words 

461 are (rules/S10, #718). 

462 

463 A numeral is I to X by shape, written with its periods or without 

464 ('VI.', the German ordinal), save that a single letter written 

465 with its period is an initial (rules/T5). The vocabulary's own 

466 numerals of two or more letters ('ii' to 'iv', `tags` carrying 

467 `vocab:suffix`) are the generation whatever stands around them, 

468 the vocabulary settling them; the rest ('vi' to 'x', and the 

469 one-letter 'i' and 'v') are weighed: 

470 

471 - an initial in front makes the numeral a name word: `preceding` 

472 is the first token of the piece in front, read for layout, and 

473 None where the slot never asks (the given part after a family 

474 comma, where 'Chang, Andy C I' reads suffix 'I', v1's reading); 

475 - a Title-case numeral in a name of mixed case leans to the name, 

476 as a Title-case member of the ambiguous class does 

477 (`numeral_leans_to_the_name`). 

478 

479 In the given part after a family comma (`preceding` None) a 

480 one-letter numeral is the generation only where the vocabulary 

481 lists it, rules/C9's "one-character suffix word": no count is 

482 asked there (S5), and an unlisted letter is the middle initial 

483 ('SMITH, JOHN X'). 

484 

485 is_initial_shaped, not is_initial: this asks whether the preceding 

486 piece looks like part of an initial run, which is a question 

487 about layout, and #320 narrowed the tag to initials that can 

488 really stand in for a name. Reading the tag here made '씨.' stop 

489 suppressing the fork and cost 'John 씨. V' its family name. 

490 

491 `one_case` is ParseState.one_case: in a name written in one case 

492 the word in front is read as its capital would be, so a bare 'j' 

493 is initial-shaped as 'J' is (rules/S10, #721's review: 'john j v' 

494 reads as 'JOHN J V'), while 'é', 'ж' or an uncased word, whose 

495 capitals are not, stay as they were. None (the maiden take's 

496 superset view passes it) asks neither case question, which admits 

497 more and so stays a superset.""" 

498 stem = text.rstrip(".") 

499 if not stem or _ROMAN.match(stem) is None: 

500 return False 

501 if len(stem) == 1: 

502 # rules/T5: "A one-letter word written with its period is an 

503 # initial" 

504 if len(text) > 1: 

505 return False 

506 if preceding is None: 

507 return "vocab:suffix" in tags 

508 elif "vocab:suffix" in tags: 

509 return True 

510 elif one_case is False and stem.istitle(): 

511 return False 

512 return (preceding is None 

513 or not (is_initial_shaped(preceding) 

514 or one_case and is_initial_shaped(preceding.upper()))) 

515 

516 

517# rules/C3: "a numeral ending the part, or standing before the listed 

518# suffix words it ends with, that the trailing fork reads as the generation is 

519# no name word" -- asked of the shape-only numerals, 

520# the listed ones being suffix words to every count that asks it already; 

521# decisions/C3 (#893) 

522def ends_in_a_generation(texts: Sequence[str], one_case: bool | None, 

523 ) -> bool: 

524 """Whether the second of `texts`, two words of a name, is a 

525 numeral of two or more letters that the trailing fork reads as the 

526 generation behind the first. It reads no tags, so a listed numeral 

527 ('III') answers True too: each caller passes only a word it has not 

528 already read as a suffix, which leaves the unlisted VI to IX, and 

529 finds the two words itself, the numeral ending the name words past 

530 any suffix words behind it.""" 

531 last = texts[-1] 

532 return (len(last.rstrip(".")) >= 2 

533 and reads_as_generation(last, frozenset(), texts[-2], one_case)) 

534 

535 

536#: What a word of a clause S1 sets apart is: a title, a suffix, or a 

537#: word that is both, its place in the name choosing (rules/S1). 

538SetApartKind = Literal["title", "suffix", "dual"] 

539 

540 

541# rules/S13: "Written with a period inside it, whatever case the name is 

542# in" -- the writing that settles a member, asked of its text since a 

543# clause word carries no shape tag (decisions/S13, #810, #1088) 

544def dotted_member(word: str, lexicon: Lexicon) -> bool: 

545 """Whether a word of a delimited clause is a member of the 

546 ambiguous class (S4) written with a period inside it ('M.A', 

547 'M.A.'), a comma the clause keeps on it left off (rules/N1). A 

548 period ending the clause is extract's escape, not this.""" 

549 bare = word.strip(COMMA_STRIP) 

550 return ("." in bare.strip(".") 

551 and _normalize(bare).replace(".", "") 

552 in lexicon._sets.suffix_acronyms_ambiguous) 

553 

554 

555# rules/S1: "a clause wholly of words the vocabulary reads as no name 

556# is set apart from the name" -- the word's half; `set_apart` is the 

557# clause's. Its suffix half is `suffix_as_written`'s, so a credential 

558# joined by a slash or a hyphen is one here as it is bare; a word its 

559# periods join is asked first, then a dotted member, and a joined word 

560# holding a member after the suffix test, each member left to S13's 

561# position test (decisions/S1, #792, #1088; decisions/S3, #1131, #1138) 

562def set_apart_kind(word: str, lexicon: Lexicon, 

563 ) -> SetApartKind | Literal["member"] | None: 

564 """What a word in a delimited clause is to S1's set-apart reading: 

565 a title, a suffix (a word `suffix_as_written` reads, joined 

566 credentials included, or one its periods join, 

567 `period_joined_credential`), both, a member of the ambiguous class 

568 written with a period inside it (`dotted_member`), a joined word 

569 holding one (`joined_member`, 'MA/PhD') or a word its periods join 

570 holding one ('Msc.Ed'), which S13 settles after the name only, or 

571 None where the vocabulary reads it as a name or not at 

572 all. A comma the clause keeps on its word is no part of it 

573 (rules/N1).""" 

574 bare = word.strip(COMMA_STRIP) 

575 folded = _normalize(bare) 

576 acronym = folded.replace(".", "") 

577 sets = lexicon._sets 

578 # rules/S1: "one joined by a slash, a hyphen or a period (S3) too, 

579 # every chunk counting" -- a word with interior periods read here as 

580 # at the end of a name ('(Msc.Ed)', '(Lt.Gov)'; not '(Bob.PhD)'), 

581 # the period test asked at C level first (decisions/S3, #1131) 

582 joined = ("." in folded and folded not in sets.titles 

583 and acronym not in sets.suffix_acronyms) 

584 title = folded in sets.titles or joined and period_joined_title( 

585 bare, lexicon) 

586 if joined and not title and period_joined_credential(bare, lexicon): 

587 # rules/S3: "a joined word holding a member is a member itself" 

588 # -- 'Msc.Ed' as 'MA/PhD', settled by S13's position (#1138) 

589 return "member" if _holds_a_member(bare, lexicon) else "suffix" 

590 # a member of the ambiguous class, the set asked inline as the 

591 # necessary half of `dotted_member`, so no other word pays its 

592 # frame: `suffix_as_written` would read a dotted member as a suffix 

593 # wherever it stands, and reads no other member as one 

594 if acronym in sets.suffix_acronyms_ambiguous: 

595 if title: 

596 return "title" 

597 return "member" if "." in bare and dotted_member( 

598 bare, lexicon) else None 

599 # the sets and the joiners asked first, at C level, the necessary 

600 # half of `suffix_as_written`, so a word it could never read (a 

601 # nickname) pays no frame 

602 suffix = ((acronym in sets.suffix_acronyms or folded in sets.suffix_words 

603 or "-" in folded or "/" in folded) 

604 and suffix_as_written(folded, bare, lexicon)) 

605 # rules/S3: "a joined word holding a member is a member itself" -- 

606 # settled after the name only, as S13 settles one written alone 

607 # (decisions/S3, #1138) 

608 if suffix and not title and joined_member(bare, lexicon): 

609 return "member" 

610 if title: 

611 return "dual" if suffix else "title" 

612 return "suffix" if suffix else None 

613 

614 

615#: Single letters each followed by a period ('R.A.'), the writing that 

616#: makes a word that is a title too a set of initials (rules/S1). 

617_DOTTED_INITIALS = re.compile(r"(?:[^\W\d_]\.)+") 

618 

619#: A word written as initials: one or two letters, with or without a 

620#: period, or single letters each followed by a period ('JP', 'Md', 

621#: 'MD.', 'A.M.', 'R.E.S.'). 

622_INITIALS_SHAPE = re.compile(r"[^\W\d_]{1,2}\.?|" + _DOTTED_INITIALS.pattern) 

623 

624 

625# rules/S1: "A credential written as initials before a name word stays 

626# the nickname, and so does any word of its clause" -- asked of each 

627# chunk of a credential joined by a slash or a hyphen, so it reads 

628# before a name word as its split spelling does (decisions/S1, #792, 

629# #1088) 

630def reads_as_initials(word: str, kind: SetApartKind, 

631 one_case: bool | None, lexicon: Lexicon) -> bool: 

632 """Whether a word of a clause S1 would set apart counts, before a 

633 name word of its comma part, as the initials the person goes by: a 

634 credential written in their shape that is no generation word, and a 

635 word that is a title too only written with a period after each 

636 letter ('V.C.') or in capitals in a name of mixed case ('VC'), 

637 Title case reading as the title it also is and capitals in a name 

638 written in one case saying nothing (S6); a title alone never. A 

639 member of the ambiguous class counts as the credential it is 

640 settled as. `one_case` is ParseState.one_case. A joined credential 

641 counts where any of its chunks would ('JP/MD', 'MD/PhD'), as its 

642 words written apart do, and one the vocabulary lists whole never 

643 ('NP-C'), a run of its chunks listed whole being one chunk 

644 ('PhD/NP-C' is 'PhD', 'NP-C', as `_joined_chunks` cuts it). A 

645 chunk is asked as the word it is, with no further cut by this 

646 function, so its loop is one level deep.""" 

647 bare = word.strip(COMMA_STRIP) 

648 # a credential the vocabulary lists whole ('NP-C', 'SHRM-CP') is one 

649 # word, not two S3 joins, and has no other spelling written apart 

650 if kind == "suffix" and ("/" in bare or "-" in bare) and not ( 

651 _listed_whole(bare, lexicon)): 

652 # a word with no cut S3 admits has no chunk to ask; unreached by 

653 # a parse, where a joined word not listed whole is a suffix only 

654 # through a cut 

655 for chunk in _joined_chunks(bare, lexicon) or (): 

656 if _shaped_as_initials(chunk, set_apart_kind(chunk, lexicon), 

657 one_case, lexicon): 

658 return True 

659 return False 

660 # rules/S1: "a credential S3 reads through chunks joined by a slash, 

661 # a hyphen or a period counts where any of its chunks would" -- a 

662 # period-joined word's chunks asked as a slash's are ('JP.MD' as 

663 # 'JP/MD'), one listed whole ('M.D.', 'MD.PhD') never (#1131) 

664 if (kind == "suffix" and "." in bare.strip(".") 

665 and _normalize(bare).replace(".", "") 

666 not in lexicon._sets.suffix_acronyms 

667 and period_joined_credential(bare, lexicon)): 

668 # a single letter before a glued honorific is the initial it is 

669 # written as ('J.씨', the one chunk the every-chunk test lets 

670 # count as nothing) 

671 return any(len(chunk) == 1 and chunk.isalpha() 

672 or _shaped_as_initials(chunk, set_apart_kind(chunk, lexicon), 

673 one_case, lexicon) 

674 for chunk in _period_chunks(bare) or ()) 

675 return _shaped_as_initials(bare, kind, one_case, lexicon) 

676 

677 

678def _shaped_as_initials(bare: str, 

679 kind: SetApartKind | Literal["member"] | None, 

680 one_case: bool | None, lexicon: Lexicon) -> bool: 

681 """`reads_as_initials` for one word, or one listed run of a joined 

682 word, its kind as `set_apart_kind` gives it; a run holding a joiner 

683 never matches the initials shape.""" 

684 return ((kind == "suffix" or kind == "member" or kind == "dual" and ( 

685 _DOTTED_INITIALS.fullmatch(bare) is not None 

686 or one_case is False and bare.isupper())) 

687 and _INITIALS_SHAPE.fullmatch(bare) is not None 

688 and _normalize(bare) not in lexicon._sets.suffix_words) 

689 

690 

691def set_apart(words: Sequence[str], 

692 kinds: Sequence[SetApartKind], 

693 behind_a_credential: bool, lexicon: Lexicon) -> bool: 

694 """rules/S1's clause tests over the words of a delimited clause, 

695 each already found to be no name by `set_apart_kind` (or, after 

696 the name, a member its writing settles, rules/S13): a clause of 

697 nothing but title modifiers and styles is no title ('(UK)', 

698 '(Hon)'), a lone title of address may be the name the person goes 

699 by ('(Sir)', '(Mr)': a title addressing the given name, or a 

700 salutation that may end the given part, rules/H8), and a clause 

701 of titles alone straight behind a credential qualifies that 

702 credential ('FRCS (SN)'). `behind_a_credential` is whether the 

703 word in front of the clause was read as a suffix, which extract, 

704 running before any word is read, passes as False.""" 

705 sets = lexicon._sets 

706 folded = [_normalize(w.strip(COMMA_STRIP)) for w in words] 

707 if all(f in sets.title_modifiers or f in sets.title_styles 

708 for f in folded): 

709 return False 

710 if len(folded) == 1 and (folded[0] in sets.given_name_titles 

711 or folded[0] in sets.after_given_titles): 

712 return False 

713 return not (behind_a_credential and "suffix" not in kinds 

714 and "dual" not in kinds) 

715 

716 

717# rules/S10: "a Title-case numeral in a name of mixed case leans to the 

718# name" -- the fork weighed it and the writing declined it, so it is 

719# reported as a declined member of the ambiguous class is (#752) 

720def numeral_leans_to_the_name(text: str, tags: Set[str], 

721 preceding: str | None, 

722 one_case: bool | None) -> bool: 

723 """Whether `reads_as_generation` declined a numeral for its Title 

724 case alone: two or more letters, unlisted, in a name of mixed case, 

725 and no initial in front (which makes it a name word unweighed).""" 

726 return (one_case is False and text.rstrip(".").istitle() 

727 and len(text.rstrip(".")) >= 2 and "vocab:suffix" not in tags 

728 and reads_as_generation(text, tags, preceding, None)) 

729 

730 

731def is_listed_numeral(text: str, tags: Set[str]) -> bool: 

732 """A numeral the vocabulary lists in two or more letters ('III'): 

733 not in question, so its reading is never reported (rules/S10).""" 

734 stem = text.rstrip(".") 

735 return (len(stem) >= 2 and "vocab:suffix" in tags 

736 and _ROMAN.match(stem) is not None) 

737 

738 

739# rules/S10: "a numeral written in lower case in a name of mixed case is 

740# the generation and reports nothing" -- the one writing that settles 

741# the fork, since nobody writes an initial in lower case beside 

742# capitals. Asked by the walk, which takes such a numeral as any suffix 

743# word and records no call, and by the report on a numeral before a 

744# credential (`reads_as_a_reported_numeral`). 

745def numeral_settled_by_case(text: str, one_case: bool | None) -> bool: 

746 """Whether a numeral the trailing fork reads is lower case in a 

747 name written in more than one case. `one_case` is 

748 ParseState.one_case; None (nobody asked) settles nothing.""" 

749 return one_case is False and text.islower() 

750 

751 

752# rules/S10: "either reading is reported" -- the one question the two 

753# reports on a numeral a post-nominal follows ask (assign's, and the 

754# maiden take's for a numeral its clause keeps): the fork would read 

755# this numeral, and its writing does not settle it (#721) 

756def reads_as_a_reported_numeral(text: str, tags: Set[str], 

757 preceding: str, 

758 one_case: bool | None) -> bool: 

759 """Whether a numeral the walk left a name word, with `preceding` 

760 in front of it, is one the fork would weigh and so reports: one it 

761 reads as the generation, or declines for its Title case.""" 

762 return ((reads_as_generation(text, tags, preceding, one_case) 

763 or numeral_leans_to_the_name(text, tags, preceding, one_case)) 

764 and not numeral_settled_by_case(text, one_case)) 

765 

766 

767# #544: a single-letter roman numeral ('V', 'v', 'I.'), in any case, 

768# is excluded for its SHAPE -- one letter is how a middle initial is 

769# written, and rules/S3 retires single-character matches for the 

770# same reason -- not for being a generation: a multi-letter suffix 

771# word ('III', 'Jr') anchors and runs like any other. So it neither 

772# anchors an ambiguous member behind it nor counts toward C4's 

773# multi-word credential run. It still peels exactly as before; this 

774# answers only those two questions. 

775def is_single_letter_numeral(text: str) -> bool: 

776 """One letter, optionally followed by periods, that is a roman 

777 numeral ('V', 'v', 'I.', 'X').""" 

778 letters = text.rstrip(".") 

779 return len(letters) == 1 and _ROMAN.match(letters) is not None 

780 

781 

782# rules/T5: "A one-letter word written with its period is an initial, 

783# in a script that writes initials, and so is a bare unaccented Latin 

784# capital, A to Z" 

785def is_initial(text: str) -> bool: 

786 """'A.' / 'j.' / bare capital -- v1's is_an_initial, narrowed to 

787 scripts that HAVE initials (#320). v1's \\w is Unicode-aware and 

788 matched CJK too, which made period-written CJK honorifics ('씨.') 

789 fail is_suffix_strict -- the veto in _is_suffix_strict_n, NOT the 

790 vocabulary: suffix_as_written has no veto, so classify tagged '씨.' 

791 'vocab:suffix' either way, and is_suffix_lenient took it either way 

792 too. Downstream of that one strict-test No, the glued honorific in 

793 a name carrying such a token went unpeeled ('田中さん 様.').""" 

794 return is_initial_shaped(text) and not in_initialless_script(text) 

795 

796 

797def is_one_case(texts: Sequence[str]) -> bool: 

798 """Whether a name is written wholly in ONE case -- all upper or all 

799 lower alike -- and so carries no case EVIDENCE about any letter in 

800 it (rules/P8, #383/#479). The caller passes the name's OWN 

801 words: a maiden marker's clause and any delimited (nickname) 

802 content are not among them, and appending one must not flip the 

803 reading of words that did not change. 

804 

805 Mirrors the SHAPE of the comparison the R5 gate in 

806 `_render.capitalized` makes, not its SPAN: R5 joins every token but 

807 the suffixes, nickname and maiden content included, while 

808 classify's caller hands in only the name's own words (rules/P3's 

809 own-words doctrine, see above) -- so a clause-bearing name can be 

810 one-case to this function and mixed to R5 (measured: 

811 `'JUAN GARCIA Y LOPEZ née Jones'` is one case here, mixed there), 

812 and a name with a cased suffix mixed here and one-case there 

813 (`'john e jones III'`). Not shared by import today -- render is a 

814 layer this module does not reach into -- and #492 left the two 

815 spans apart by decision (decisions/R5, "THE R5 / PARSER SPLIT"). 

816 

817 `Sequence`, not `Iterable`: the caller passes a list it already 

818 built rather than a fresh generator, so `is_one_case` costs one 

819 profiler frame per parse rather than one per token (#475). 

820 

821 A CASELESS script answers True, harmlessly: `'محمد و علي'.upper()` 

822 is the string itself, so the comparison holds. Its callers are 

823 classify, segment (only where C2's flag on a tail part asks) and 

824 script_segment's `_one_case`; the first two record the answer as 

825 `ParseState.one_case`, and script_segment does not; the decisions 

826 that read it each also require the token they judge to be CASED: 

827 classify's connective-or-initial fork asks for a token whose own 

828 `upper()` and `lower()` differ, `ambiguous_lean` -- which the 

829 suffix readers in `_pieces`, `_group` and `_assign` reach through 

830 `listed_lean` -- returns no lean for a caseless token, and 

831 `caps_shape_candidate` requires 

832 `isupper()`. A caseless letter is none of those, so a caseless 

833 name never reaches a decision this gates, and "one case" is the 

834 honest verdict for text that has only one. 

835 """ 

836 joined = " ".join(texts).translate(_CASELESS_LETTERS) 

837 return joined in (joined.upper(), joined.lower()) 

838 

839 

840#: Which way the WRITING leans for a member of the ambiguous 

841#: credential class; None is no lean at all. Named so the two 

842#: predicates that answer it -- `ambiguous_lean` here and 

843#: `_pieces.listed_lean`, which wraps it -- carry the same three-value 

844#: type rather than a bare `str`. Under mypy's `strict_equality` that 

845#: makes a misspelled comparison (`== "credentail"`) an error at the 

846#: two call sites that branch on the answer, where a `str` return 

847#: leaves it silently False forever -- which is what the value is FOR: 

848#: `_pieces.peel_trailing` peels or declines on it. 

849#: `period_joined_vocab`'s own verdict is spelled inline for the same 

850#: reason; it has one caller shape and no wrapper to keep in step. 

851Lean = Literal["credential", "name"] 

852 

853#: How a member's writing leans, by what the member is (rules/S11): 

854#: an acronym's capitals are the credential, the lower case of a suffix 

855#: word written `title_case_is_name` is the suffix, and any other suffix 

856#: word's writing (an agnomen's, `Junior`'s) says nothing (#1039). 

857Cue = Literal["acronym", "word", "none"] 

858 

859 

860# #289's credential lean, rules/S6: "Written case is evidence beside 

861# the count (S4), and it speaks only in a name written in more than 

862# one case" -- the WRITING evidence that decides ahead of the 

863# words-to-spare count (history: decisions/S6). 

864def ambiguous_lean(text: str, one_case: bool, 

865 cue: Cue = "acronym") -> Lean | None: 

866 """Which way the WRITING leans for a member of the ambiguous 

867 credential set: "credential", "name", or None for no lean at all. 

868 

869 None is the fall-through to rules/S4's count, and it is the 

870 answer for three inputs. A name written wholly in one case says 

871 nothing about any word in it. A member written wholly in lower 

872 case says nothing either -- lower is how most of a mixed-case 

873 name is written, so it is not a contrast. And a CASELESS token 

874 ('씨', '毛') can be written against nothing, so neither test 

875 fires and the count decides, which is what keeps this rule out of 

876 a caseless script by construction. 

877 

878 `one_case` is the recorded fact (ParseState.one_case), taken over 

879 the name's OWN words -- handed in rather than recomputed, because 

880 three sites read this and a fact two of them derived apart is the 

881 bug the field exists to prevent 

882 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

883 

884 The caller decides MEMBERSHIP: this answers only about the 

885 writing. Periods do not disturb either test, '.' having no case, 

886 so 'MA.' leans as 'MA' does -- the lean reads CASE, not periods, 

887 and the dotted spelling is the vocabulary's own question 

888 (suffix_as_written). 

889 

890 `cue` is what the member is (rules/S11). A suffix WORD that is 

891 also a name and whose Title case is its writing as a name ("word", 

892 'fils', 'kc', written `title_case_is_name`) leans the other way at 

893 one end: its lower case in a mixed-case name is the suffix 

894 ("credential", the suffix reading), its capitals say nothing (a 

895 surname is often written so), and Title case leans to the name as 

896 an acronym's does. Any other ("none": an agnomen, 'Neto', written 

897 in the case of the name around it; 'Junior', whose Title case is 

898 the generation's writing too) never leans (#1039). 

899 """ 

900 if one_case or cue == "none": 

901 return None 

902 # a script the table gives no case is caseless here too (#1222); no 

903 # default vocabulary member is written in one, so only a caller's 

904 # lexicon reaches this with a Georgian word 

905 if (cased := text.translate(_CASELESS_LETTERS)).upper() == cased.lower(): 

906 return None # caseless: no contrast to read 

907 if text.isupper(): 

908 return "credential" if cue == "acronym" else None 

909 if text.islower(): 

910 return "credential" if cue == "word" else None 

911 return "name" 

912 

913 

914def lexicon_cue(n: str, lexicon: Lexicon) -> Cue: 

915 """The `ambiguous_lean` cue of the folded member `n`, read off the 

916 lexicon by a caller that has no tags to read (`is_wholly_suffix`); 

917 `_pieces.listed_lean` reads the same answer off classify's tags.""" 

918 if n in lexicon._sets.suffix_words_ambiguous: 

919 return ("word" if n in lexicon._sets.title_case_name_words 

920 else "none") 

921 return "acronym" 

922 

923 

924_DOTTED = re.compile(r"(?:" + _LETTER + r"\.)+") 

925# rules/T7: "a run of single letters joined by full stops" -- two or 

926# more letters, each closed by a stop but the last, whose stop is 

927# optional ('E.T.', 'J.R.R', #1296), and the same run rules/H10 reads as 

928# a title ('U.S.', 'U.S', the closing stop optional as 

929# `period_joined_vocab`'s shape verdict lets it be); _RUN_LETTER is one letter of it 

930# with its stop. _render holds a copy of each (tests/v2/test_regex_sync.py) 

931_LETTER_RUN = re.compile(r"(?:" + _LETTER + r"\.)+" + _LETTER + r"\.?") 

932 

933 

934_RUN_LETTER = re.compile(_LETTER + r"\.?") 

935 

936 

937def is_letter_run(text: str) -> bool: 

938 """Two or more single letters joined by full stops ('J.P.', 'J.R.R'), 

939 the way a person's initials are written run together: rules/T7's 

940 run, and the shape rules/C16 reads as a name after the comma behind 

941 one name word whatever it spells (#1238).""" 

942 return _LETTER_RUN.fullmatch(text) is not None 

943 

944 

945# #544: the CHUNKED spelling -- two or more runs of letters, each 

946# closed by a period ('M.Eng.', 'L.Ac.'). Both callers compare the 

947# period-free letters against the listed member, so the chunks must 

948# spell it; one chunk ('Ma.', 'Ed.') is the single trailing period and 

949# stays outside the gate. 

950_CHUNKED = re.compile(r"(?:(?:" + _LETTER + r")+\.){2,}") 

951 

952 

953def _dotted(text: str) -> bool: 

954 """Written with its periods: one after each letter ('M.A.', 

955 'J.D.'), the acronym's own spelling, or -- since #544 -- two or 

956 more letter chunks each closed by a period ('M.Eng.', 'L.Ac.'), the 

957 spelling a member with a lower-case tail is written in. A single 

958 trailing period ('Ma.', 'Ed.', 'Ms.') is the abbreviation shape any 

959 word can wear -- the honorific's, a name's -- and is not the gate's 

960 "written with periods" (rules/S3). Until #296's review the gate 

961 was "any period", and 'Smith, Ms.' passed it as the degree.""" 

962 return (_DOTTED.fullmatch(text) is not None 

963 or _CHUNKED.fullmatch(text) is not None) 

964 

965 

966# the combining marks (Mn) Unicode names ARABIC, every block's, which 

967# `_LETTER` does not count (decisions/H2): the hamza a decomposed أ or إ 

968# is written with, and the short vowels, so a title's chunk and the name 

969# after its stop are found in NFD text ('أ.محمد', 'أ.د.أحمد') as in NFC 

970# (#1149) 

971_ARABIC_MARKS = "[" + "".join(re.escape(chr(c)) for c in range(0x0600, 0x10F00) if unicodedata.category(chr(c)) == "Mn" and unicodedata.name(chr(c), "").startswith("ARABIC")) + "]" # noqa: E501 

972# a letter as T8 reads one: `_LETTER`, an Arabic mark counted with it 

973_GLUED_LETTER = r"[^\W\d_](?:" + _MARKS + "|" + _ARABIC_MARKS + ")*" 

974# rules/T8: "glued to the next at its full stop" -- the shapes 

975# `glued_cuts` reads (decisions/T8 (#1230, #1235)): one chunk of letters 

976# closed by a stop with something after it 

977_GLUED_CHUNK = re.compile(r"((?:" + _GLUED_LETTER + r")+)\.(?=\S)") 

978# a run of two or more single letters closed by stops, a letter after 

979# it (the name is `glued_cuts`' to find) 

980_GLUED_RUN = re.compile(r"(?:" + _GLUED_LETTER + r"\.){2,}(?=[^\W\d_])") 

981#: a letter (its marks with it, so NFD text passes), a full stop and a 

982#: letter: the C-level test `_script_segment` asks before `glued_cuts` 

983GLUED_SHAPE = re.compile(_GLUED_LETTER + r"\.[^\W\d_]") 

984# the Thai vowel and tone marks (Mn), which `_LETTER` does not count: 

985# nearly every Thai name writes one ('สุดา', 'ใจดี'), so without them the 

986# name after a Thai title's stop is never found (#1166) 

987_THAI_MARKS = "[\u0e31\u0e34-\u0e3a\u0e47-\u0e4e]" 

988# one word of letters, apostrophes and hyphens: what can follow a chunk 

989# and be a name; a zero-width non-joiner or joiner between two letters 

990# is part of the word, as Persian spells one ('محمد\u200cرضا', #1149) 

991_GLUED_WORD = re.compile( 

992 r"(?:" + _LETTER + r")(?:" + _LETTER + "|" + _THAI_MARKS + "|" 

993 + _ARABIC_MARKS + r"|['’\-]|[\u200c\u200d](?=[^\W\d_]))*") 

994 

995 

996def is_name_word(text: str) -> bool: 

997 """Whether `text` is wholly one name word as T8 reads the name after 

998 a stop: letters, apostrophes and hyphens, a letter's marks counted 

999 with it and a joiner between two letters. rules/T9 asks it of the 

1000 name after a title's slash, so a word holding a delimiter, a digit 

1001 or another slash is never cut.""" 

1002 return _GLUED_WORD.fullmatch(text) is not None 

1003 

1004 

1005def _is_cased_letter(chunk: str) -> bool: 

1006 """One letter in a script with case: the initial T8 reads alone 

1007 (rules/T8); a single letter in a script without case is read alone 

1008 only where it is listed, as a title or a given name written short.""" 

1009 return len(chunk) == 1 and chunk.upper() != chunk.lower() 

1010 

1011 

1012def _reads_alone(chunk: str, lexicon: Lexicon) -> bool: 

1013 """A chunk the parser reads on its own before a full stop: one 

1014 letter in a script with case, a transliteration digraph rules/H2 

1015 names, a listed title that is no saint particle, or a listed given 

1016 name written short (decisions/period-joined-words, #1255). A single 

1017 letter in a script without case is read alone only where it is 

1018 listed (Thai 'ศ.', #1166); a run of them is T7's run in any script.""" 

1019 chunk = unicodedata.normalize("NFC", chunk) 

1020 if _is_cased_letter(chunk): 

1021 return True 

1022 n = _normalize(chunk) 

1023 sets = lexicon._sets 

1024 if n in _DIGRAPH_INITIALS or n in sets.given_name_abbreviations: 

1025 return True 

1026 return is_title_chunk(chunk, lexicon) 

1027 

1028 

1029def _claimed_after_the_stop(w: str, lexicon: Lexicon) -> bool: 

1030 """Whether the folded word W after a glued full stop is an 

1031 unambiguous title or suffix word, and so no name (rules/T8): the 

1032 one test `glued_cuts` and `glued_saint_cut` ask of it.""" 

1033 sets = lexicon._sets 

1034 return w in sets.titles or ( 

1035 w in sets.suffix_acronyms 

1036 and w not in sets.suffix_acronyms_ambiguous) or ( 

1037 (w in sets.suffix_words or w in sets.credential_words) 

1038 and w not in sets.suffix_words_ambiguous) 

1039 

1040 

1041def glued_cuts(text: str, lexicon: Lexicon) -> tuple[int, ...]: 

1042 """Where a word glued to the next at a full stop divides (T8, 

1043 #1230, #1235): the offset after each stop at which a chunk the 

1044 parser reads alone (`_reads_alone`) meets a name, so the word reads 

1045 as it does with a space there ('Dr.John' as 'Dr. John', 

1046 'Ц.Сандаг-Очир' as 'Ц. Сандаг-Очир', 'Yu.A.Chibrikova' as 'Yu. A. 

1047 Chibrikova'). A run of single letters stays one chunk before the name 

1048 ('J.R.Smith' as 'J.R. Smith', rules/T7), while titles glued to each 

1049 other divide at each stop, as they read written apart ('Lt.Gov.John' 

1050 as 'Lt. Gov. John'). Empty where the vocabulary reads the word whole 

1051 (a suffix spelled without its stops, 'M.Sc', 'M.Sc.'; a title listed 

1052 whole), and wherever the 

1053 word does not divide through to its end: at a word in lower case 

1054 ('Dr.med', 'G.ppe'), at one closed by its own stop or followed by 

1055 another chunk ('Dr.Med.', 'J.Smith.', 'Dr.John.Smith'), and at an 

1056 unambiguous title or credential after the stop ('Dr.MD').""" 

1057 # a run of single letters alone is the walk's first answer below, 

1058 # `titled` being false there ('J.R.R.'), asked before the fold's frame 

1059 if _LETTER_RUN.fullmatch(text): 

1060 return () 

1061 sets = lexicon._sets 

1062 n = _normalize(text) 

1063 bare = n.replace(".", "") 

1064 # a title listed whole is read whole, as a suffix spelled without its 

1065 # stops is: with its stops, or without them where no initial ends it 

1066 # ('Dr.Ma' where a caller lists 'drma'; 'Dr.A.' divides, 'dra' being 

1067 # the title and the initial T8 reads behind one) 

1068 if (bare in sets.suffix_acronyms or n in sets.titles 

1069 or bare in sets.titles and len(unicodedata.normalize( 

1070 "NFC", n.rsplit(".", 1)[-1])) > 1): 

1071 return () 

1072 low = text.lower() 

1073 dotted = _dotted_titles(sets.titles) 

1074 if len(low) != len(text): 

1075 # offsets in `low` would not be the text's 

1076 dotted = () 

1077 cuts: list[int] = [] 

1078 at = 0 

1079 titled = False 

1080 # the cuts stand only where the word divides through to its end: a 

1081 # name closing it ('Yu.A.Chibrikova'), or initials closing one a 

1082 # title opens ('Dr.J.', 'Dr.J.R.'); never initials alone ('Kim 

1083 # Yu.A.', the surname-first initials #1254 asks about), an initial 

1084 # opening a chunk that stays whole ('Q.R.ST.'), nor a word holding a 

1085 # delimiter or a digit, which no chunk or name matches ('M.D./Ph.D.') 

1086 while True: 

1087 if _LETTER_RUN.fullmatch(text, at): 

1088 return tuple(cuts) if titled else () 

1089 d = (dotted_title_end(low, at, dotted) 

1090 if dotted and low.startswith(dotted, at) else None) 

1091 if d is not None and ( 

1092 (run := _GLUED_RUN.match(text, at)) is not None 

1093 and run.end() > d): 

1094 # a run of single letters running past the title is T7's 

1095 # run of initials ('พ.ต.ส.สมชาย') 

1096 d = None 

1097 if d is not None: 

1098 # a title listed with its stops is one chunk, read alone 

1099 # (#1319: 'พล.ต.ต.สุรศักดิ์', 'พ.อ.หญิงวาสนา') 

1100 titled = titled or not cuts 

1101 if d == len(text): 

1102 return tuple(cuts) 

1103 nxt = _GLUED_CHUNK.match(text, d) 

1104 if (low.startswith(dotted, d) 

1105 and dotted_title_end(low, d, dotted) is not None) or ( 

1106 nxt is not None and is_title_chunk(nxt.group(1), lexicon)): 

1107 cuts.append(d) 

1108 at = d 

1109 continue 

1110 end, letter = d, False 

1111 elif (run := _GLUED_RUN.match(text, at)) is not None: 

1112 # a run of initials before the name stays one word (T7) 

1113 end, letter = run.end(), True 

1114 else: 

1115 m = _GLUED_CHUNK.match(text, at) 

1116 if m is None or not _reads_alone(m.group(1), lexicon): 

1117 return () 

1118 end = m.end() 

1119 letter = _is_cased_letter( 

1120 unicodedata.normalize("NFC", m.group(1))) 

1121 if not letter and is_title_chunk(m.group(1), lexicon): 

1122 titled = titled or not cuts 

1123 nxt = _GLUED_CHUNK.match(text, end) 

1124 if nxt is not None and is_title_chunk(nxt.group(1), lexicon): 

1125 # titles glued to each other divide at each stop, as 

1126 # the titles written apart read ('Lt.Gov.John', 

1127 # 'Maj.Gen.John', a phrase H9 reads) 

1128 cuts.append(end) 

1129 at = end 

1130 continue 

1131 word = _GLUED_WORD.match(text, end) 

1132 # its first letter with case, so a modifier letter opening it 

1133 # ('m.ʿali') does not hide a word in lower case; a script with 

1134 # no case gives none, and divides 

1135 if word is None or next( 

1136 (c.islower() for c in word.group() if c.upper() != c.lower()), 

1137 False): 

1138 return () 

1139 initial = len(unicodedata.normalize("NFC", word.group())) == 1 

1140 tail = text[word.end():] 

1141 # a word closed by its own stop is a field or a name closed by 

1142 # one ('Dr.Med.', 'J.Smith.'), save an initial behind a title 

1143 # ('Dr.J.'); one followed by another chunk stays whole 

1144 # ('Dr.John.Smith'), save an initial opening the next division 

1145 # ('Yu.A.Chibrikova') 

1146 if tail == "." and not (initial and not letter): 

1147 return () 

1148 if len(tail) > 1 and not initial: 

1149 return () 

1150 w = _normalize(word.group()) 

1151 if _claimed_after_the_stop(w, lexicon): 

1152 return () 

1153 cuts.append(end) 

1154 at = end 

1155 if word.end() == len(text) or tail == ".": 

1156 return tuple(cuts) if titled or not initial else () 

1157 

1158 

1159@functools.lru_cache(maxsize=16) 

1160def _dotted_titles(titles: frozenset[str]) -> tuple[str, ...]: 

1161 """The titles of a script without case listed with a full stop 

1162 inside ('พ.ต.อ', 'พ.อ.หญิง'), longest first: one tuple per 

1163 vocabulary, so a word opening with none of them is told by a C-level 

1164 `startswith` alone. A cased title written with its stops ('dr.c', 

1165 'mgr.a') is left out: glued, it keeps the reading decisions/T8's 

1166 #1305 entry decided, a title and the initial behind it 

1167 ('Dr.C.Meera'), where a caseless script writes no initials.""" 

1168 return tuple(sorted((t for t in titles if "." in t and t == t.upper()), 

1169 key=len, reverse=True)) 

1170 

1171 

1172@functools.lru_cache(maxsize=16) 

1173def title_prefixes(titles: frozenset[str]) -> tuple[str, ...]: 

1174 """Every listed title, a tuple for a C-level `startswith`: what may 

1175 stand behind a title only in a phrase glued in front (rules/W6).""" 

1176 return tuple(titles) 

1177 

1178 

1179def dotted_title_end(low: str, at: int, 

1180 dotted: tuple[str, ...]) -> int | None: 

1181 """Where a title listed with its stops, opening `low` at `at`, ends 

1182 as a word of its own: past its own full stop, or, where its last 

1183 chunk is more than one letter ('พ.อ.หญิง'), right before a letter 

1184 of a script without case. A last chunk of one letter needs its 

1185 stop, being the initial it spells otherwise ('น.สมชาย' is no 

1186 'น.ส' + 'มชาย', 'พ.ต.อนุชา' no 'พ.ต.อ' + 'นุชา'), and a letter with 

1187 case after a longer chunk goes on the word ('Lt.Colin', not 'Lt.Col' 

1188 + 'in'); None where none does (#1319).""" 

1189 for t in dotted: 

1190 if not low.startswith(t, at): 

1191 continue 

1192 end = at + len(t) 

1193 if end == len(low): 

1194 return end 

1195 if low[end] == ".": 

1196 return end + 1 

1197 c = low[end] 

1198 last = t.rsplit(".", 1)[-1] 

1199 if len(unicodedata.normalize("NFC", last)) > 1 and c.isalpha() and ( 

1200 c.upper() == c.lower()): 

1201 return end 

1202 return None 

1203 

1204 

1205def glued_saint_cut(text: str, lexicon: Lexicon) -> int | None: 

1206 """The offset after the stop where a listed saint particle is glued 

1207 to the name it opens ('Sta.Ana', 'St.John', 'STE.MARIE'): the 

1208 particle, one full stop and one name word whose first letter with 

1209 case is a capital, nothing after it; None for any other word 

1210 (rules/T8, #1071). The word is one name word wherever it stands, 

1211 and divides here only as the last word of a part (`_script_segment` 

1212 asks that).""" 

1213 # the C-level matches first, which turn away nearly every word 

1214 # ('J.R.R.', 'Lt.Gov.'), before the fold's frame 

1215 m = _GLUED_CHUNK.match(text) 

1216 if m is None: 

1217 return None 

1218 word = _GLUED_WORD.fullmatch(text, m.end()) 

1219 if (word is None 

1220 or _normalize(m.group(1)) not in lexicon._sets.saint_particles 

1221 or next( 

1222 (c.islower() for c in word.group() 

1223 if c.upper() != c.lower()), 

1224 True)): 

1225 return None 

1226 # an unambiguous title or suffix word after the stop is no name 

1227 # ('St.MD', 'St.Jr') 

1228 if _claimed_after_the_stop(_normalize(word.group()), lexicon): 

1229 return None 

1230 return m.end() 

1231 

1232 

1233def is_initial_chunk(chunk: str) -> bool: 

1234 """Initials before a full stop, as T8's report asks of the chunks it 

1235 cut (rules/T8): one letter in a script with case, a run of them 

1236 ('J.R'), or a transliteration digraph rules/H2 names ('Yu'), and no 

1237 title or given name written short.""" 

1238 parts = chunk.split(".") 

1239 if len(parts) == 1 and _normalize(chunk) in _DIGRAPH_INITIALS: 

1240 return True 

1241 return all(_is_cased_letter(unicodedata.normalize("NFC", part)) 

1242 for part in parts) 

1243 

1244 

1245def is_title_chunk(chunk: str, lexicon: Lexicon) -> bool: 

1246 """A listed title that is no saint particle, read as a chunk before 

1247 a full stop (rules/T8; a saint particle glued to a name is one name 

1248 word, `glued_saint_cut`).""" 

1249 sets = lexicon._sets 

1250 n = _normalize(chunk) 

1251 return n not in sets.saint_particles and ( 

1252 n in sets.titles or n in sets.titles_ambiguous 

1253 or n in sets.title_modifiers or n in sets.title_styles) 

1254 

1255 

1256def is_dotted_title(text: str, n: str, lexicon: Lexicon) -> bool: 

1257 """A run of single letters joined by full stops ('U.S.', 'P.D.') 

1258 whose spelling without them is a title written `dotted` 

1259 (`Lexicon.dotted_titles`, rules/H10, #490); `n` is the folded 

1260 text, which both callers already have.""" 

1261 return (n.replace(".", "") in lexicon._sets.dotted_titles 

1262 and _LETTER_RUN.fullmatch(text) is not None) 

1263 

1264 

1265# #563: exactly two single letters, each closed by a period -- the way 

1266# a given and a middle initial are written run together ('M.J.', 

1267# 'G.J.'). The trailing period is optional, as `period_joined_vocab`'s 

1268# shape verdict lets it be. 

1269_PAIRED_INITIALS = re.compile(_LETTER + r"\." + _LETTER + r"\.?") 

1270 

1271 

1272def is_paired_initials(text: str) -> bool: 

1273 """Two single letters run together with periods ('M.J.'): the one 

1274 unlisted dotted shape a person's own initials take, so after a 

1275 comma it is a name until something in front of it, or another 

1276 dotted word beside it, says it is a credential (rules/C5). 

1277 Three or more letters ('X.Y.Z.') and any longer chunk ('B.Tech.') 

1278 are outside it.""" 

1279 return _PAIRED_INITIALS.fullmatch(text) is not None 

1280 

1281 

1282# rules/S3: "Paired initials are the exception, as C5 defines them, in a 

1283# script that writes capitals" -- the script half of that clause, which 

1284# classify asked inline until #752 (decisions/S3 (#864), 

1285# decisions/vocabulary-model (#752)). C5's comma reading asks the bare 

1286# `is_paired_initials`: after a comma a caseless pair reads as a name 

1287# too ('John Smith, พ.บ.' given 'พ.บ.'), and moving it here would change 

1288# that reading. 

1289def is_cased_paired_initials(text: str) -> bool: 

1290 """Paired initials (`is_paired_initials`) in a script that writes 

1291 capitals: a text with a case mapping, so 'M.J.' and 'm.j.' but not 

1292 Thai 'พ.บ.', which is how that script writes an abbreviation. 

1293 The same compiled pattern as `is_paired_initials`, asked here 

1294 rather than through it so a dotted token pays one frame, not 

1295 two.""" 

1296 return (_PAIRED_INITIALS.fullmatch(text) is not None 

1297 and text.upper() != text.lower()) 

1298 

1299 

1300# rules/S12: "a credential written split across a space reads as one 

1301# word" -- one chunk of up to five letters, with or without its period 

1302# ('Pharm.', 'D', 'Sc.'), the shape both words of a split credential 

1303# take. The C-level half classify asks of every adjacent pair before 

1304# the fold is looked up. 

1305SPLIT_CHUNK = re.compile(r"(?:" + _LETTER + r"){1,5}\.?") 

1306 

1307 

1308# mechanisms.md#ONE-PREDICATE-PER-QUESTION ("exactly one predicate answers it and every other site calls that one") 

1309# -- the split credential's one test, asked by classify, which tags 

1310# the pair for group's merge and `_comma._pieces`, and by 

1311# `is_wholly_suffix` for the Ph./D. answer. decisions/phd-merge, 

1312# decisions/vocabulary-model (#752) 

1313def split_pair(first: str, second: str, lexicon: Lexicon) -> str | None: 

1314 """Whether two adjacent words are one credential written split 

1315 across a space, and so read as one unit -- answered with the PIECE 

1316 TAG the merged pair carries, or None. 

1317 

1318 "suffix": 'Ph.' then 'D.', with or without their periods, in any 

1319 case, where the lexicon lists `phd` as unambiguous suffix 

1320 vocabulary (a credential, or a suffix word) -- v1's fix_phd, 

1321 merged as an unambiguous suffix wherever it stands but the head 

1322 of the string (decisions/phd-merge); under a lexicon that does 

1323 not, None, the pair being the two words it is written as. 

1324 

1325 "split": any other pair of short chunks (`SPLIT_CHUNK`) whose 

1326 period-free concatenation is unambiguous suffix vocabulary while 

1327 the two are not both suffix vocabulary on their own ('Pharm. D.', 

1328 'Pharm D', 'MB ChB' where 'chb' is unlisted) and neither is a 

1329 particle or a connective, which join name words. The merged piece is 

1330 a member of the ambiguous class, which the count decides (rules/S4, 

1331 rules/C4). Its first chunk has two or more letters: a single 

1332 letter opening the pair is a middle initial far more often (FEC 

1333 writes 'SMITH, JOHN G. MR.', and 'G. MR.' folds to the listed 

1334 'gmr'), so 'M. Sc.' and 'M. D.' stay two words. Two dotted single 

1335 letters are the one opening letter asked further, and asked of 

1336 #872's predicate rather than a copy: in a script with capitals 

1337 they are paired initials (`is_cased_paired_initials`), the reading 

1338 rules/S3 gives them joined, so only a caseless script's pair can 

1339 merge, and not one in a script that writes no abbreviations (Han, 

1340 hangul, kana: '博. 士.' is no dotted '博士'), which leaves no 

1341 default entry such a fold. 

1342 

1343 Where the merge may happen (never at the head of the string, 

1344 rules/S2; a member pair only in a main segment and in the part 

1345 after a comma) is the caller's question, not this one's.""" 

1346 if _PH.fullmatch(first) is not None and _D.fullmatch(second) is not None: 

1347 # rules/S12: "is a credential only where the lexicon lists `phd`" 

1348 # -- as unambiguous suffix vocabulary of either kind, as the 

1349 # joined spelling reads it; elsewhere the two words, the fold 

1350 # below being `phd` itself, which an ambiguous suffix word would 

1351 # admit as a member. decisions/phd-merge (#1000) 

1352 sets = lexicon._sets 

1353 return ("suffix" if "phd" in sets.suffix_acronyms 

1354 and "phd" not in sets.suffix_acronyms_ambiguous 

1355 or "phd" in sets.suffix_words 

1356 and "phd" not in sets.suffix_words_ambiguous else None) 

1357 if (SPLIT_CHUNK.fullmatch(first) is None 

1358 or SPLIT_CHUNK.fullmatch(second) is None): 

1359 return None 

1360 a, b = first.rstrip("."), second.rstrip(".") 

1361 if composed_len(a) < 2 and ( 

1362 composed_len(b) != 1 or not first.endswith(".") 

1363 or not second.endswith(".") 

1364 or is_cased_paired_initials(first + second) 

1365 # a script that writes no abbreviations is not wearing an 

1366 # abbreviation's periods, as rules/S3 reads it joined 

1367 or in_unabbreviating_script(first + second)): 

1368 return None 

1369 fold = _normalize(a + b) 

1370 if (fold in lexicon._sets.suffix_acronyms_ambiguous 

1371 or not (fold in lexicon._sets.suffix_acronyms 

1372 or fold in lexicon._sets.suffix_words)): 

1373 return None 

1374 na, nb = _normalize(a), _normalize(b) 

1375 if ((na in lexicon._sets.suffix_acronyms or na in lexicon._sets.suffix_words) 

1376 and (nb in lexicon._sets.suffix_acronyms 

1377 or nb in lexicon._sets.suffix_words)): 

1378 return None 

1379 # a particle or a connective joins name words, which is what it is 

1380 # doing beside one ('DE A JUNIOR', the A a surname written short); 

1381 # written with its period a letter is an initial, not the connective 

1382 # it spells ('SAM E.', rules/T5) 

1383 for written, n in ((first, na), (second, nb)): 

1384 if not written.endswith(".") and (n in lexicon._sets.particles 

1385 or n in lexicon._sets.conjunctions): 

1386 return None 

1387 return "split" 

1388 

1389 

1390def suffix_as_written(n: str, text: str, lexicon: Lexicon) -> bool: 

1391 """Counts as a suffix as written, with NO initial veto (the veto 

1392 differs by caller): unambiguous suffix vocabulary, an ambiguous 

1393 acronym written with periods ('M.A.' yes, 'Ma' no), or a credential 

1394 joined by '-' or '/' (`_joined_credential`, 'MD/PhD'). `n` is 

1395 _normalize(text), passed in so callers normalize once. 

1396 

1397 Single source for classify's "vocab:suffix" tag and the segment/ 

1398 assign predicates. The ambiguous subset is EXCLUDED from the plain 

1399 membership test: in the real data suffix_acronyms_ambiguous is a 

1400 subset of suffix_acronyms, and without the exclusion the period 

1401 gate is dead code (bare 'Ed'/'Jd' would silently become suffixes). 

1402 """ 

1403 # acronyms may be written with periods ('M.B.A.'): the ACRONYM 

1404 # membership alone uses the period-free form (v1's is_suffix 

1405 # removed periods only for the suffix_acronyms test); suffix WORDS 

1406 # match on the plain normalized form 

1407 a = n.replace(".", "") 

1408 if a in lexicon._sets.suffix_acronyms_ambiguous and _dotted(text): 

1409 return True 

1410 if ((a in lexicon._sets.suffix_acronyms 

1411 and a not in lexicon._sets.suffix_acronyms_ambiguous) 

1412 or (n in lexicon._sets.suffix_words 

1413 and n not in lexicon._sets.suffix_words_ambiguous)): 

1414 return True 

1415 # the joiners asked in C first, so a word holding neither pays no 

1416 # frame 

1417 return ("-" in n or "/" in n) and _joined_credential(text, lexicon) 

1418 

1419 

1420#: What joins the letter chunks of the caps shape's joined spelling 

1421#: ('PU-PH', `_joined_capitals`); a joined credential is cut by 

1422#: `_JOINER_SPLIT`, which keeps the joiners. 

1423_JOINERS = re.compile(r"[-/]") 

1424 

1425 

1426def _member(chunk: str, lexicon: Lexicon) -> bool: 

1427 """Whether CHUNK is a member of the ambiguous class (S4), however 

1428 written ('MA', 'Ma', 'M.A', 'M.A.'): an acronym once its periods are 

1429 removed, or a suffix word, that is a name too.""" 

1430 folded = _normalize(chunk) 

1431 return (folded.replace(".", "") in lexicon._sets.suffix_acronyms_ambiguous 

1432 or folded in lexicon._sets.suffix_words_ambiguous) 

1433 

1434 

1435def _settles(chunk: str, lexicon: Lexicon) -> bool: 

1436 """Whether CHUNK, one word or one listed run of a joined word's cut, 

1437 settles a member beside it: a credential that is no name 

1438 (`settles_a_member`), or a member written with a period inside it 

1439 ('M.A').""" 

1440 return (settles_a_member(chunk, lexicon) 

1441 or "." in chunk and dotted_member(chunk, lexicon)) 

1442 

1443 

1444# rules/S1: "a credential that is no name, or a member its periods 

1445# settle, says which" -- the credential half, asked of a clause word 

1446# and of a joined word's chunk alike: a generation, a numeral, an 

1447# honorific or a word that is a title too says nothing of the kind, 

1448# 'Ed Jr' being a name a person goes by (decisions/S1, #1138) 

1449def settles_a_member(word: str, lexicon: Lexicon) -> bool: 

1450 """Whether WORD, a comma it is written against left off (rules/N1), 

1451 is a credential that is no name: it counts as a suffix as written 

1452 (a member its periods settle, 'M.A.', included) and is no 

1453 generation, no honorific and no title. A joined word not listed 

1454 whole is one where a chunk of its cut is ('PhD/Jr', not 'Jr/Sr').""" 

1455 bare = word.strip(COMMA_STRIP) 

1456 if ("/" in bare or "-" in bare) and not _listed_whole(bare, lexicon): 

1457 return any(_settles(c, lexicon) 

1458 for c in _joined_chunks(bare, lexicon) or ()) 

1459 folded = _normalize(bare) 

1460 sets = lexicon._sets 

1461 return (suffix_as_written(folded, bare, lexicon) 

1462 and folded not in sets.generation_words 

1463 and folded not in sets.honorific_words 

1464 and folded not in sets.titles) 

1465 

1466 

1467def joined_member(word: str, lexicon: Lexicon) -> bool: 

1468 """Whether WORD, joined by '/' or '-' and not listed whole ('NP-C'), 

1469 cuts (`_joined_chunks`) into pieces one of which is a member of the 

1470 ambiguous class that does not count as a suffix as written 

1471 ('MA/PhD', 'M.A/PhD', 'MA/MBA'; not 'M.A./PhD'). `set_apart_kind` 

1472 asks it of a word `suffix_as_written` reads, making that word a 

1473 member S13 settles by its position; `_report_delimited_members` 

1474 asks it of any joined nickname, so a joined word of members alone 

1475 reports as its words written apart do.""" 

1476 if not ("/" in word or "-" in word) or _listed_whole(word, lexicon): 

1477 return False 

1478 return any(_member(c, lexicon) 

1479 and not suffix_as_written(_normalize(c), c, lexicon) 

1480 for c in _joined_chunks(word, lexicon) or ()) 

1481 

1482 

1483def member_word(word: str, lexicon: Lexicon) -> bool: 

1484 """Whether a word of a delimited clause, a comma the clause keeps 

1485 on it left off (rules/N1), is a member of the ambiguous class (S4), 

1486 however written.""" 

1487 return _member(word.strip(COMMA_STRIP), lexicon) 

1488 

1489 

1490def _listed_whole(word: str, lexicon: Lexicon) -> bool: 

1491 """Whether the suffix vocabulary lists WORD whole, its joiners 

1492 included ('NP-C', 'OTR/L'): as a suffix word, or as an acronym once 

1493 its periods are removed. A member of an ambiguous class counts as 

1494 listed.""" 

1495 folded = _normalize(word) 

1496 return (folded in lexicon._sets.suffix_words 

1497 or folded.replace(".", "") in lexicon._sets.suffix_acronyms) 

1498 

1499 

1500#: The joiners of a joined credential, kept: 'MS/OTR/L' splits to 

1501#: 'MS', '/', 'OTR', '/', 'L', the chunks at the even places. 

1502_JOINER_SPLIT = re.compile(r"([-/])") 

1503 

1504 

1505# bounded as `_longest_marker` is, for the reason given there: a set 

1506# per lexicon, so 16 bounds many-lexicon churn without evicting in 

1507# normal use 

1508@functools.lru_cache(maxsize=16) 

1509def _joined_span(words: frozenset[str]) -> int: 

1510 """How many chunks the most-joined of WORDS holds: the longest run a 

1511 listed word can be. Cached per set, which hashes once.""" 

1512 return max((w.count("/") + w.count("-") for w in words), default=0) + 1 

1513 

1514 

1515# rules/S3: "a run of chunks the vocabulary lists whole, its slash or 

1516# hyphen included, is one credential" -- the joiner inside 'NP-C' or 

1517# 'OTR/L' is how that credential is spelled, not a joiner between two 

1518# (decisions/S3, #1103) 

1519def _joined_chunks(text: str, lexicon: Lexicon) -> list[str] | None: 

1520 """A cut of TEXT at some of its joiners into pieces that each count 

1521 as a suffix as written or are a member of the ambiguous class 

1522 however written ('MA', 'M.A'), a run of chunks the vocabulary lists 

1523 whole among them, with the fewest pieces ('MS/OTR/L' is 'MS', 'OTR/L'; 

1524 'CCC/SLP/L' is 'CCC', 'SLP/L'; 'APRN-FNP-C' is 'APRN', 'FNP-C'; 

1525 'MD-PhD' is 'MD', 'PhD'), or None where no cut gives such pieces 

1526 ('MD-Jones', 'MD/'). No piece is the whole of TEXT: each caller has 

1527 asked TEXT whole already, and a word listed whole that it refused 

1528 (one that is a name too) would otherwise be asked again for ever. 

1529 A piece is no longer than the most-joined listed word, so a long 

1530 chain of joiners costs linear time.""" 

1531 parts = _JOINER_SPLIT.split(text) 

1532 n = (len(parts) + 1) // 2 # the chunks 

1533 span = max(_joined_span(lexicon._sets.suffix_words), 

1534 _joined_span(lexicon._sets.suffix_acronyms)) 

1535 # pieces[k]: the fewest pieces cutting the first k chunks (0 where 

1536 # none does, past the start); start[k]: where the last of them starts 

1537 pieces = [0] * (n + 1) 

1538 start = [0] * (n + 1) 

1539 for i in range(n): 

1540 if i and not pieces[i]: 

1541 continue 

1542 for j in range(i + 1, min(n - (i == 0), i + span) + 1): 

1543 piece = "".join(parts[2 * i:2 * j - 1]) 

1544 # a run must be listed whole, which a chunk alone need not be 

1545 if not piece or j > i + 1 and not _listed_whole(piece, lexicon): 

1546 continue 

1547 # a member is a chunk however written; `_joined_credential` 

1548 # asks that a chunk beside it settles it (#1138) 

1549 if ((not pieces[j] or pieces[i] + 1 < pieces[j]) 

1550 and (suffix_as_written(_normalize(piece), piece, lexicon) 

1551 or _member(piece, lexicon))): 

1552 pieces[j] = pieces[i] + 1 

1553 start[j] = i 

1554 if not pieces[n]: 

1555 return None 

1556 cut: list[str] = [] 

1557 j = n 

1558 while j: 

1559 i = start[j] 

1560 cut.append("".join(parts[2 * i:2 * j - 1])) 

1561 j = i 

1562 cut.reverse() 

1563 return cut 

1564 

1565 

1566# rules/S3: "a word whose chunks are joined by a hyphen or a slash 

1567# reads as a suffix when every chunk counts as a suffix as written" -- 

1568# the stricter test, every chunk rather than any, because a hyphen also 

1569# joins names (decisions/S3 (#752)); a chunk is a run the vocabulary 

1570# lists whole where one is (#1103) 

1571def _joined_credential(text: str, lexicon: Lexicon) -> bool: 

1572 """Whether TEXT is two or more chunks joined by '-' or '/', cut so 

1573 that each is non-empty and counts as a suffix as written (listed, 

1574 and not a bare member of the ambiguous class, a run listed whole 

1575 counting as one chunk) or is a member of that class however 

1576 written, where one chunk at least settles every such member 

1577 (`_settles`), and not every chunk a single ASCII character, and -- 

1578 joined by a hyphen -- not written as a hyphenated name is ('MD/PhD', 'M.A.-Ph.D.', 'MA/PhD', 

1579 'M.A/PhD', 'PhD-Md', 'md-phd', 'PhD/NP-C', but not 'MA/MBA', 

1580 'MA/Jones', 'Smith-Jones', 'I-V', 'Ae-Ra', 'Ae-ra' or 'MD/'). The 

1581 writing is read first, so a hyphenated name ('Smith-Jones') is 

1582 never cut.""" 

1583 # a slash joins no name, so a word holding one takes no cue 

1584 if "/" not in text: 

1585 # rules/S3: "a word joined by a hyphen and written the way a 

1586 # hyphenated name is, its first chunk in Title case and every 

1587 # other in Title case or lower case, is a name word" -- where a 

1588 # credential's chunks are not (decisions/S3 (#752)); its periods 

1589 # are not the chunk's ('I.' is 'i'), as in a word split at its 

1590 # periods 

1591 named = True 

1592 for k, c in enumerate(text.split("-")): 

1593 bare = c.replace(".", "") 

1594 named = (len(bare) > 1 and bare[0].isupper() and bare[1:].islower() 

1595 or k > 0 and bare.islower()) 

1596 if not named: 

1597 break 

1598 if named: 

1599 return False 

1600 chunks = _joined_chunks(text, lexicon) 

1601 if chunks is None: 

1602 return False 

1603 # rules/S3: "a member of the ambiguous class (S4) is a chunk too, 

1604 # however it is written, where the word holds a chunk that settles 

1605 # it" -- a credential that is no name, or a member its periods 

1606 # settle; a word of bare members alone has nothing to settle it 

1607 # (decisions/S3, #1138) 

1608 unsettled = any(_member(c, lexicon) 

1609 and not suffix_as_written(_normalize(c), c, lexicon) 

1610 for c in chunks) 

1611 if unsettled and not any(_settles(c, lexicon) for c in chunks): 

1612 return False 

1613 # rules/S3: "Every chunk the vocabulary matches is a single ASCII 

1614 # character" -- the numerals and the digit, which are about 

1615 # generations, make no joined word a suffix either ('Jack I-V') 

1616 for c in chunks: 

1617 bare = c.replace(".", "") 

1618 if len(bare) > 1 or not bare.isascii(): 

1619 return True 

1620 return False 

1621 

1622 

1623# rules/S3: "a word with interior periods reads as a suffix when 

1624# every one of its period-separated chunks counts as a suffix as 

1625# written" -- the joined words' every chunk, the periods being the one 

1626# sign the word is joined at all (decisions/S3, #1131) 

1627def period_joined_credential(text: str, lexicon: Lexicon) -> bool: 

1628 """Whether TEXT, cut at its periods (`_period_chunks`), is chunks 

1629 that each count as a suffix as written or are a member of the ambiguous 

1630 class, one chunk at least settling every such member (`_settles`), 

1631 and not every chunk the vocabulary matches a single ASCII character 

1632 ('Msc.Ed', 'JD.CPA'; not 'Bob.PhD', 'Ma.Ed' or 'X.Y.I.'). A word 

1633 whose last chunk is a glued honorific ('J.씨') reads as one too: 

1634 the honorific is the suffix there and the chunk before it the 

1635 initial it is written as (rules/W2). The chunks are two or more, 

1636 save one where the word's periods all stand at its edge beside an 

1637 ampersand or a semicolon ('MD.&', as 'MD.& PhD' writes it).""" 

1638 chunks = _period_chunks(text) 

1639 if chunks is None: 

1640 return False 

1641 sets = lexicon._sets 

1642 if _normalize(chunks[-1]) in sets.honorific_tails: 

1643 return True 

1644 unsettled = False 

1645 for c in chunks: 

1646 folded = _normalize(c) 

1647 if suffix_as_written(folded, c, lexicon): 

1648 continue 

1649 # rules/S11: "the word is part of that one word and is weighed 

1650 # only by the shape the joined word wears" -- no chunk claim 

1651 # for a suffix word that is also a name ('MD.Filho', whose Filho 

1652 # MD would otherwise settle as a member) 

1653 if folded in sets.suffix_words_ambiguous or not _member(c, lexicon): 

1654 return False 

1655 unsettled = True 

1656 if unsettled and not any(_settles(c, lexicon) for c in chunks): 

1657 return False 

1658 # rules/S3: "Every chunk the vocabulary matches is a single ASCII 

1659 # character" -- a numeral or the digit says nothing of a credential 

1660 return not all(len(c) == 1 and c.isascii() for c in chunks) 

1661 

1662 

1663def _period_chunks(text: str) -> list[str] | None: 

1664 """TEXT cut at its periods, or None where it holds none inside it 

1665 (one chunk where every period stands at the word's edge and an '&' 

1666 or ';' there keeps one off the outer end: 'MD.&', ';.MD'). 

1667 ASCII punctuation beside an interior period is no part of the chunk 

1668 ('MD.&PhD'); at the word's outer edges only its periods, a glued 

1669 semicolon (rules/C10, 'Jr.;') and an ampersand joining the next 

1670 credential ('MD.& PhD') are, so a word wearing any other there 

1671 is no period-joined word at all, as a single word or a slash word 

1672 wearing it is a name word ('Msc.Ed!', 'Msc.Ed.]', '[Msc.Ed]' as 

1673 'MD!', 'MD/PhD]'). A chunk of nothing but punctuation is no 

1674 chunk.""" 

1675 if "." not in text.strip("."): 

1676 return None 

1677 i, j = 0, len(text) 

1678 while i < j and text[i] in string.punctuation: 

1679 i += 1 

1680 while j > i and text[j - 1] in string.punctuation: 

1681 j -= 1 

1682 if any(c not in ".;&" for c in text[:i] + text[j:]): 

1683 return None 

1684 chunks = [b for c in text[i:j].split(".") 

1685 if (b := c.strip(string.punctuation))] 

1686 return chunks or None 

1687 

1688 

1689def _holds_a_member(text: str, lexicon: Lexicon) -> bool: 

1690 """Whether a chunk of TEXT cut at its periods (`_period_chunks`) is 

1691 a member of the ambiguous class that does not count as a suffix as 

1692 written ('Ed' in 'Msc.Ed').""" 

1693 return any(_member(c, lexicon) 

1694 and not suffix_as_written(_normalize(c), c, lexicon) 

1695 for c in _period_chunks(text) or ()) 

1696 

1697 

1698def period_member(word: str, lexicon: Lexicon) -> bool: 

1699 """Whether WORD, a word with interior periods that is no acronym 

1700 listed once its periods are removed, is 

1701 a period-joined credential (`period_joined_credential`) holding a 

1702 member of the ambiguous class ('Msc.Ed'): `joined_member`'s 

1703 question for a word the periods join (rules/S3, #1131).""" 

1704 bare = word.strip(COMMA_STRIP) 

1705 folded = _normalize(bare) 

1706 return ("." in folded 

1707 and folded.replace(".", "") not in lexicon._sets.suffix_acronyms 

1708 and period_joined_credential(bare, lexicon) 

1709 and _holds_a_member(bare, lexicon)) 

1710 

1711 

1712# rules/H5: "a word with interior periods every one of whose chunks is 

1713# a title chains without a final period" -- 'Lt.Gov', where the 

1714# periods join nothing but titles (decisions/H5, #1131) 

1715def period_joined_title(text: str, lexicon: Lexicon) -> bool: 

1716 """Whether TEXT, cut at its periods, is two or more chunks every 

1717 one of which is title vocabulary ('Lt.Gov', 'Lt.Col'; not 

1718 'Dr.PhD' or 'St.John').""" 

1719 chunks = [_normalize(c) for c in text.split(".") if c] 

1720 return len(chunks) >= 2 and all( 

1721 c in lexicon._sets.titles for c in chunks) 

1722 

1723 

1724def _is_suffix_strict_n(n: str, text: str, lexicon: Lexicon, 

1725 one_case: bool | None = None) -> bool: 

1726 # rules/T4: "in a name written wholly in one case, which says 

1727 # nothing about any letter in it, a bare letter is an initial 

1728 # wherever its capital would be" -- so the veto takes 'v' where it 

1729 # takes 'V' (#727). Lower case first, at C level: a capital is 

1730 # is_initial's already, and only a caller with the fact passes it 

1731 if is_initial(text) or ( 

1732 one_case and len(text) == 1 and text.islower() 

1733 and _INITIAL.fullmatch(text.upper()) is not None): 

1734 # period-written ambiguous acronyms are exempt from the veto 

1735 return _dotted(text) and \ 

1736 n.replace(".", "") in lexicon._sets.suffix_acronyms_ambiguous 

1737 return suffix_as_written(n, text, lexicon) 

1738 

1739 

1740def is_suffix_strict(text: str, lexicon: Lexicon, 

1741 one_case: bool | None = None) -> bool: 

1742 """v1's is_suffix: suffix_as_written with the initial veto ('V.' in 

1743 'John V. Smith' is a middle initial, not roman five). 

1744 

1745 `one_case` is whether the name's own words are written in one 

1746 case (ParseState.one_case): where they are, a bare lowercase 

1747 letter is the initial its capital is (rules/T4) and is vetoed as 

1748 its capital is. None or False is the veto by the writing alone, 

1749 which is v1's.""" 

1750 return _is_suffix_strict_n(_normalize(text), text, lexicon, one_case) 

1751 

1752 

1753def is_suffix_lenient(text: str, lexicon: Lexicon) -> bool: 

1754 """v1's is_suffix_lenient: suffix_words accepted unconditionally, 

1755 bypassing the initial veto -- only safe in unambiguous positions 

1756 (after a comma).""" 

1757 n = _normalize(text) 

1758 return (n in lexicon._sets.suffix_words 

1759 and n not in lexicon._sets.suffix_words_ambiguous) \ 

1760 or _is_suffix_strict_n(n, text, lexicon) 

1761 

1762 

1763#: The suffix delimiters every policy has, beside the comma. rules/C10: 

1764#: "The semicolon, the hyphen and the slash are delimiters by default" 

1765#: -- "no policy removes them, as none removes the comma", so a 

1766#: policy's extra_suffix_delimiters add to them. decisions/C10 (D15, 

1767#: #889). 

1768BUILTIN_SUFFIX_DELIMITERS = frozenset({";", "-", "/"}) 

1769 

1770#: The built-in delimiters read glued to a word or inside one. rules/C10: 

1771#: "a built-in hyphen or slash parts only standing alone" -- glued, it 

1772#: is the word's own ('al-', 'MD/PhD'). decisions/C10 (#889). 

1773BUILTIN_GLUED_DELIMITERS = frozenset({";"}) 

1774 

1775 

1776def delimiter_cores(policy_delimiters: frozenset[str]) -> frozenset[str]: 

1777 """The built-in suffix delimiters with the configured ones, 

1778 surrounding whitespace stripped: ' - ' -> '-', the cores that part 

1779 a trailing suffix part STANDING ALONE. Whitespace-padded 

1780 delimiters surface as standalone tokens; the stripped core is what 

1781 tokenize produced.""" 

1782 if not policy_delimiters: 

1783 return BUILTIN_SUFFIX_DELIMITERS 

1784 return BUILTIN_SUFFIX_DELIMITERS | frozenset( 

1785 d.strip() for d in policy_delimiters if d.strip()) 

1786 

1787 

1788def glued_cores(policy_delimiters: frozenset[str]) -> frozenset[str]: 

1789 """The cores read glued to one end of a word or inside one: the 

1790 semicolon and every configured core, never a built-in hyphen or 

1791 slash that the caller did not declare (BUILTIN_GLUED_DELIMITERS). 

1792 A configured core that is itself a word (' and ') is in the set: 

1793 `glued_stem`'s callers ask `glues` before reading it glued, while 

1794 `is_wholly_suffix`'s in-word split does not ('MDandPhD').""" 

1795 if not policy_delimiters: 

1796 return BUILTIN_GLUED_DELIMITERS 

1797 return BUILTIN_GLUED_DELIMITERS | frozenset( 

1798 d.strip() for d in policy_delimiters if d.strip()) 

1799 

1800 

1801# rules/C10: "the word keeps the delimiter in its text and reads as it 

1802# would without it" -- the word, for every site that reads one: the 

1803# tags classify writes, the comma decision's shape tests, C2's flag 

1804# and the run test below (decisions/C10). 

1805def glued_stem(text: str, cores: frozenset[str]) -> str | None: 

1806 """The word a delimiter core glued to ONE end of `text` leaves 

1807 ('MD;' -> 'MD', ';PhD' -> 'PhD', 'MD-PhD;' -> 'MD-PhD' under '-'), 

1808 or None: no core at an end of the text, a core standing alone, one 

1809 inside a word only ('MD;PhD', which splits_into_suffixes reads), or 

1810 a core that is itself a word (see glues). Every core is tried, in 

1811 sorted order, so the answer never depends on a set's iteration 

1812 order (the second review of #871: 'MD/PhD; MBA' under '/' read two 

1813 ways by hash seed). Callers test `core in text` inline first, so a 

1814 word with no core pays no frame.""" 

1815 for core in sorted(cores): 

1816 if (core in text and glues(core) and text.count(core) == 1 

1817 and len(text) > len(core)): 

1818 if text.endswith(core): 

1819 return text[:-len(core)] 

1820 if text.startswith(core): 

1821 return text[len(core):] 

1822 return None 

1823 

1824 

1825def glues(core: str) -> bool: 

1826 """Whether a delimiter core can be GLUED to a word: one written 

1827 without a letter or digit (';', '/', '-'). A core that is a word 

1828 (' and ' under a declared policy) is found inside other words by 

1829 the substring test ('Stand'), so it parts only standing alone 

1830 (rules/C10's glued bullet).""" 

1831 return not any(ch.isalnum() for ch in core) 

1832 

1833 

1834def splits_into_suffixes(text: str, cores: frozenset[str], 

1835 lexicon: Lexicon) -> bool: 

1836 """v1 expand_suffix_delimiter parity for delimiters WITHOUT 

1837 whitespace ('RN/CRNA' with '/'): the token counts as a suffix when 

1838 some core splits it into >=2 non-empty parts that are all suffixes. 

1839 A core glued to ONE word ('MD;') is is_wholly_suffix's to read, by 

1840 the test it gives that word alone (D15). The token text is never 

1841 rewritten (anti-#100): it takes Role.SUFFIX whole, which renders 

1842 'RN/CRNA' where v1 rendered 'RN, CRNA' -- the documented 

1843 divergence, release-log classified.""" 

1844 for core in cores: 

1845 if core in text: 

1846 parts = [part for part in text.split(core) if part] 

1847 if len(parts) >= 2 and all( 

1848 is_suffix_lenient(part, lexicon) for part in parts): 

1849 return True 

1850 return False 

1851 

1852 

1853# rules/S3: "a word with interior periods reads as a suffix when 

1854# every one of its period-separated chunks counts as a suffix as 

1855# written" -- "every chunk the vocabulary matches is a single ASCII 

1856# character, the roman numerals and the lone digit the vocabulary 

1857# lists, which are about generations rather than credentials". The 

1858# chunk rule and its single-character exception (decisions/S3, 

1859# #1131). 

1860def period_joined_vocab( 

1861 text: str, lexicon: Lexicon, 

1862) -> Literal["title", "suffix", "shape"] | None: 

1863 """v1's parse_pieces derivation for interior-period tokens 

1864 ('Lt.Gov.', 'Msc.Ed.', and by the ANY rule 'Mr.Smith'): ANY title 

1865 chunk makes the token a title (checked first, v1's continue); else 

1866 the token is a suffix where EVERY chunk counts 

1867 (`period_joined_credential`, #1131: 'Msc.Ed.', whose member 'ed' 

1868 'msc' settles, but not 'Bob.PhD', which the shape verdict below 

1869 reads by position). A suffix word that is also a name is a member 

1870 there, settled by a credential beside it ('M.Filho' is no suffix, 

1871 rules/S11). Returns "title", "suffix", "shape", or None. 

1872 

1873 "shape" is the third verdict and it is the absence of a claim 

1874 worth acting on (#516): two or more chunks, EVERY one of them 

1875 alphabetic, that the every-chunk test does not read as a suffix 

1876 ('Bob.PhD', 'BM.BS', #1131), chunks that are a SINGLE ASCII 

1877 CHARACTER among them. That single-character exception is the 

1878 roman-numeral accident retired narrowly: measured 2026-09-15 the 

1879 one-character suffix vocabulary is {'2', 'i', 'v'} plus the glued 

1880 CJK honorific tails, so 'John Smith R.A.I.' was reading as a 

1881 generational suffix off the chunk 'i'. CHARACTER rather than 

1882 LETTER because '2' is a digit and is in the set; ASCII because 

1883 '씨' is the single character that must KEEP its claim ('J.씨'). A 

1884 word whose every chunk counts still reads as a suffix, so 'Msc.Ed.' 

1885 and 'JD.CPA' are untouched -- the WIDE retirement, where 

1886 any chunk match yields to the shape, was measured and rejected: it 

1887 costs 'Doe, John Msc.Ed.' a real credential and re-routes the 

1888 honorific peel of '김민준씨, J.씨' for nothing this design wants 

1889 (decisions/S3). 

1890 

1891 The ALPHABETIC requirement is a SEPARATE, narrower gate on the 

1892 shape verdict alone (#516 review round, decided by the 

1893 orchestrator): a bare digit chunk is not an acronym letter by any 

1894 reading, so 'Smith, 1.4' and 'John Smith 1.4' do not join the 

1895 class by shape -- the only PROTECTED digit control this design 

1896 had was the delimited 'Bridge (1.4)', and 'Smith, 1.4' and its 

1897 no-comma twin were the gap that control did not cover, since 

1898 delimited content is excluded by a different mechanism (extract's 

1899 escape) and digits reach THIS detector, never that one. 

1900 '.isalpha()' is asked of EVERY chunk, not just the matched ones, 

1901 so a mixed token like 'X.Y.2.' is not shape-admitted either -- one 

1902 non-letter chunk is enough to say the writing is not spelling an 

1903 acronym. Chunks the vocabulary itself matches are already 

1904 alphabetic in the shipped lexicon, so this narrows only the 

1905 previously-unclaimed "shape" answer, never the "suffix" one. 

1906 

1907 The UNABBREVIATING-SCRIPT guard (the script-property table's 

1908 period_abbreviations, #1256) is a second, independent narrowing of 

1909 the same verdict, on the same reasoning `is_title_shaped` already 

1910 gives its own period-abbreviation inference (#323): a script with 

1911 no period abbreviations at all has nothing for interior periods to 

1912 ABBREVIATE, so a CJK word glued into period-separated single 

1913 characters is not spelling an acronym either -- 'John Smith 

1914 田.中.' and '김 민준 이.박.' stayed family at every release before 

1915 this gate existed, and would otherwise have joined the ambiguous 

1916 class by shape for the first time (measured regression, #516 

1917 review round). 

1918 

1919 What a "shape" verdict MEANS is the caller's question, not this 

1920 one's: classify writes the tag, and Policy.unlisted_dotted_suffixes 

1921 decides whether it is class membership. 

1922 """ 

1923 if not _PERIOD_NOT_AT_END.match(text): 

1924 return None 

1925 # rules/T8: "a saint particle glued to a name is one name word" -- 

1926 # no title chunk claims it and no dotted shape reads it 

1927 # (decisions/T8 (#1071)) 

1928 if glued_saint_cut(text, lexicon) is not None: 

1929 return None 

1930 chunks = [_normalize(c) for c in text.split(".") if c] 

1931 if any(c in lexicon._sets.titles for c in chunks): 

1932 return "title" 

1933 if period_joined_credential(text, lexicon): 

1934 return "suffix" 

1935 if (len(chunks) >= 2 and all(c.isalpha() for c in chunks) 

1936 and (text.isascii() or not in_unabbreviating_script(text))): 

1937 return "shape" 

1938 return None 

1939 

1940 

1941def ambiguous_class_member(text: str, lexicon: Lexicon) -> bool: 

1942 """Whether TEXT is a member of the LISTED ambiguous credential 

1943 class, ignoring case and policy entirely (#289/#516). 

1944 

1945 The case-INDEPENDENT half of the comma form's own candidate test 

1946 (`ambiguous_class_candidate`, below, which ALSO admits a by-shape 

1947 member where Policy allows it) and of `is_wholly_suffix`'s 

1948 credential-lean disjunct: membership by vocabulary never needs the 

1949 case fact, only the lean does. That split is what lets the comma 

1950 form's lazy gate ask membership FIRST and pay for `one_case` only 

1951 where this says yes (measured regression, #289/#516: forcing the 

1952 fact first ran `own_words` -> `tag_marker_runs` for every 

1953 single-token-after-the-comma name, none of them able to reach the 

1954 class at all). 

1955 

1956 Membership is the listed set, bare: a whole-token vocabulary match 

1957 is not in this class at all, being settled ('M.A.', 'Ph.D.', 

1958 'A.B.C.'). 

1959 

1960 Cheaper than `suffix_as_written(n, text, lexicon) or ...` would be 

1961 here, and provably the same answer for UNDOTTED text: the Lexicon 

1962 invariant that an ambiguous acronym is never also a suffix WORD 

1963 (one suffix kind per word: the vocabulary build's check 4, which 

1964 `_lexicon._check_pool` runs on a caller's reading too) and is never 

1965 counted 

1966 without periods once it IS one (`suffix_as_written`'s own 

1967 exclusion) together kill that predicate's two disjuncts once text 

1968 is known to hold no period. One frame (`_normalize`) on the common 

1969 path that never reaches the class, where the general predicate 

1970 cost at least two (mechanisms.md#ONE-PREDICATE-PER-QUESTION's cost 

1971 clause). 

1972 

1973 The '.' gate here is DELIBERATELY STRICTER than S2's own 

1974 dotted-form test (`_dotted`, a period after EACH letter or after 

1975 each of two or more letter chunks): '.' 

1976 anywhere excludes membership, so a single TRAILING period ('MA.', 

1977 'Ed.') is excluded here even though the LEAN still reads it as 

1978 the bare acronym's case ('Smith, MA.' -> suffix 'MA.', measured). 

1979 Not a contradiction: the two questions this answers -- the 

1980 comma-form CANDIDATE test below and the credential-lean disjunct 

1981 -- are never asked of those shapes, the TAG path 

1982 (`vocab:suffix-ambiguous`, read directly by the trailing peel and 

1983 the post-comma slot) and H2's leading-title shape test already 

1984 carrying them where they need to go. 

1985 """ 

1986 if "." in text: 

1987 return False 

1988 n = _normalize(text) 

1989 return (n in lexicon._sets.suffix_acronyms_ambiguous 

1990 or n in lexicon._sets.suffix_words_ambiguous) 

1991 

1992 

1993# #516's all-caps half, ONE PREDICATE for the shape test and its 

1994# WHOLE-VOCABULARY exclusion, shared by the three sites that each 

1995# needed the identical question answered (classify's tag emission, 

1996# the comma decision's caps test -- `_segment.py`'s run test until #613 

1997# moved the decision to `_comma.decide` -- and this module's own unit 

1998# tests), where it had been spelled three times over (quality-review 

1999# finding). The usual objection to sharing -- a call costing every 

2000# default-policy parse a frame it cannot use -- does not apply: the 

2001# trailing position is behind `CapsSuffixes.EVERYWHERE` (classify's 

2002# first conjunct), and the comma decision, which IS on by default, 

2003# asks C-level `isalpha()`/`isupper()` (and, for the mixed-case arm, 

2004# the case of the word's two ends) and the suffix tag first, so a comma 

2005# name with no unlisted word in capitals or in that mixed case never 

2006# reaches it. 

2007def caps_shape_candidate(text: str, lexicon: Lexicon, policy: Policy, 

2008 one_case: bool | None, *, 

2009 mixed_case: bool) -> bool: 

2010 """Whether TEXT is an UNLISTED caps-shape credential candidate: two 

2011 or more alphabetic characters, or letter chunks joined by '-' or 

2012 '/' (`_joined_capitals`, #752), no period (a period fails 

2013 `isalpha()` and the joined pattern outright, which is what excludes 

2014 the dotted spelling here for free -- no separate '.' test needed), 

2015 written in a name 

2016 `one_case` says is mixed (`one_case is False`; `None`, "not 

2017 established", declines exactly as if the name were one case). 

2018 

2019 UNLISTED means in NO wordlist at all, not merely "no whole-token 

2020 suffix vocabulary", and the roster is `_lexicon._VOCAB_FIELDS` 

2021 itself rather than a list written out here -- checked directly 

2022 against the lexicon rather than through a caller's tags (classify 

2023 is deciding the very tag a caller would read, and `_comma.decide` 

2024 asks of words classify left untagged). A hand-written roster is a second place to remember, 

2025 and it had already gone wrong: it named eleven of the thirteen 

2026 fields, leaving `surnames` and `honorific_tails` out, so 

2027 a `Lexicon` whose `surnames` listed "dupont" still read 

2028 `Jean Pierre DUPONT` as suffix `DUPONT` -- a caller listing a word 

2029 as a SURNAME and getting it read as a credential is this switch's 

2030 own worst failure, arriving through the one wordlist that says 

2031 "this is a family name" (review round, #289/#516; 

2032 `honorific_tails` was already excluded transitively, being a 

2033 subset of `suffix_words` by Lexicon invariant, and joins the 

2034 roster for completeness rather than for a behavior change). 

2035 Measured, #516 review rounds: particles, ambiguous particles, 

2036 conjunctions, bound-given heads, a maiden marker ('NEE'/'GEB') and 

2037 a title all join the shape by capitalization alone if their field 

2038 is left unchecked. 

2039 

2040 `suffix_acronyms_ambiguous` is in the roster, which also makes 

2041 this predicate stand in for `ambiguous_class_member` wherever a 

2042 caller needs "and not already a LISTED member" (undotted text's 

2043 only path into that function is the identical membership test); 

2044 its callers still test the listed set first, in C (classify's 

2045 `n not in suffix_acronyms_ambiguous`, `_comma.decide`'s 

2046 AMBIGUOUS_ACRONYM_TAG test), so a listed member never pays for 

2047 the call. 

2048 

2049 `mixed_case` admits a mixed-case word as well (`_mixed_capitals`: 

2050 'DClinPsy', 'AuD'): `_comma.decide` passes True for the part after 

2051 a comma (rules/C6, decisions/C6 (#1517)); classify passes False at 

2052 every slot it tags, `CapsSuffixes.EVERYWHERE`'s trailing positions 

2053 included, a surname typed without its apostrophe ('ONeill', 

2054 'DSouza') ending a name there. 

2055 """ 

2056 if (policy.unlisted_caps_suffixes is CapsSuffixes.OFF 

2057 or one_case is not False): 

2058 return False 

2059 if not text.isascii(): 

2060 text = unicodedata.normalize("NFC", text) 

2061 if not (len(text) >= 2 and text.isalpha() and text.isupper() 

2062 or _joined_capitals(text) 

2063 or mixed_case and _mixed_capitals(text)): 

2064 return False 

2065 return not in_any_wordlist(_normalize(text), lexicon) 

2066 

2067 

2068def _mixed_capitals(text: str) -> bool: 

2069 """Whether TEXT is an alphabetic mixed-case word that opens with two 

2070 capitals ('DClinPsy', 'MRes') or ends in one ('AuD', 'PharmD'): 

2071 written neither in capitals nor the way a name is, so the caps 

2072 shape reads it after a comma. A capital only inside the word 

2073 ('LeBron', 'McKenzie') is a name's writing and stays out, and so 

2074 does a word holding anything but letters ('Pharm-D': a mixed-case 

2075 joined arm would catch given names such as 'Jay-R'). TEXT is 

2076 NFC-composed.""" 

2077 return (len(text) >= 2 and text.isalpha() and not text.isupper() 

2078 and (text[0].isupper() and text[1].isupper() 

2079 or text[-1].isupper())) 

2080 

2081 

2082#: A word of letter chunks joined by '-' or '/' ('PU-PH', 'MD/MBA'). 

2083_JOINED_LETTERS = re.compile( 

2084 r'(?:' + _LETTER + r')+(?:[-/](?:' + _LETTER + r')+)+') 

2085 

2086 

2087# rules/S9: "an unlisted word of capitals whose letter chunks are joined 

2088# by a hyphen or a slash, one of them of two or more letters, is that 

2089# shape too" -- the caps shape's joined spelling (decisions/S9 (#752)) 

2090def _joined_capitals(text: str) -> bool: 

2091 """Whether TEXT is capitals in letter chunks joined by '-' or '/', 

2092 one chunk of two or more letters ('PU-PH', 'MS-OMPT', not 'A-B', 

2093 'MD/' or 'PU-PH2'). Its callers test `isupper()` and a joiner in C 

2094 first, so a word holding neither pays no frame.""" 

2095 if not (text.isupper() and _JOINED_LETTERS.fullmatch(text)): 

2096 return False 

2097 for chunk in _JOINERS.split(text): 

2098 if composed_len(chunk) >= 2: 

2099 return True 

2100 return False 

2101 

2102 

2103def is_caps_word(text: str) -> bool: 

2104 """Whether TEXT is alphabetic capitals once NFC-composed: `isalpha()` 

2105 is False for a combining mark, so the decomposed spelling of 

2106 'ŽŠČ' would otherwise not be a caps word (#652). Callers test the 

2107 text as written inline first, in C, and call this only for text 

2108 that is not NFC (`unicodedata.is_normalized`, also C), so composed 

2109 text pays no frame.""" 

2110 composed = unicodedata.normalize("NFC", text) 

2111 return composed.isalpha() and composed.isupper() 

2112 

2113 

2114def is_mixed_caps_word(text: str) -> bool: 

2115 """Whether TEXT, once NFC-composed, is the mixed-case word the caps 

2116 shape reads after a comma (`_mixed_capitals`: 'MRes', 'AuD'), for 

2117 the comma's C-level filters, which ask it of a word neither in one 

2118 case nor written the way a name is, or not NFC (#652).""" 

2119 return _mixed_capitals(text if text.isascii() 

2120 else unicodedata.normalize("NFC", text)) 

2121 

2122 

2123def composed(text: str) -> str: 

2124 """TEXT NFC-composed where it is not ASCII, so a letter typed as its 

2125 base and a combining mark is one letter, as the vocabulary lookup 

2126 reads it (#665). The per-token predicates (`is_initial_shaped`, 

2127 `composed_len`) fold inline instead, a call per token being the 

2128 frame budget's scaling cost.""" 

2129 return text if text.isascii() else unicodedata.normalize("NFC", text) 

2130 

2131 

2132def composed_len(text: str) -> int: 

2133 """The length of TEXT in letters as the writer sees them: code 

2134 points once NFC-composed. A caps word admitted decomposed (#652) 

2135 is longer than its composed twin, and the two-letter pair test 

2136 (`John Smith, MÁ`) counts letters.""" 

2137 return len(text if text.isascii() else unicodedata.normalize("NFC", text)) 

2138 

2139 

2140#: The marks a given-name key keeps: the tilde on n and the cedilla on 

2141#: c, which spell other letters in Spanish and Catalan (Peña, Llorenç), 

2142#: where an acute or grave accent or a diaeresis is how the same name 

2143#: is spelled with or without them (José, Jose). 

2144_KEPT_MARKS = frozenset({("n", "\u0303"), ("c", "\u0327")}) 

2145 

2146 

2147def given_name_key(text: str) -> str: 

2148 """`text` folded as `Lexicon.given_names` is matched: the 

2149 `_normalize` fold, with the accents and the diaeresis dropped and 

2150 the tilde on n and the cedilla on c kept. tools/es_given_names.py 

2151 and tools/pt_given_names.py write their lists with this same fold.""" 

2152 out: list[str] = [] 

2153 for ch in unicodedata.normalize("NFD", _normalize(text)): 

2154 if unicodedata.combining(ch) and not ( 

2155 out and (out[-1], ch) in _KEPT_MARKS): 

2156 continue 

2157 out.append(ch) 

2158 return unicodedata.normalize("NFC", "".join(out)) 

2159 

2160 

2161def is_listed_given_name(text: str, lexicon: Lexicon) -> bool: 

2162 """Whether `text` is in `lexicon.given_names`, as written or by 

2163 `given_name_key`, so a caller's entry "José" matches as written 

2164 and a list written without accents matches "José" too (rules/O6's 

2165 veto, #959).""" 

2166 names = lexicon._sets.given_names 

2167 return bool(names) and (_normalize(text) in names 

2168 or given_name_key(text) in names) 

2169 

2170 

2171def in_any_wordlist(n: str, lexicon: Lexicon) -> bool: 

2172 """Whether the folded word `n` is in ANY of the lexicon's wordlists 

2173 (`_lexicon._VOCAB_FIELDS`, the whole roster but four): the caps 

2174 shape's "unlisted" (`caps_shape_candidate`), where a word a caller 

2175 listed even as a SURNAME must never become a credential. 

2176 

2177 The four left out: `title_phrases`, whose entries are two words and 

2178 so never one; `titles_ambiguous`, a title that may be a given 

2179 name, which outside a title phrase is read as the unlisted word it 

2180 is there (rules/H9: "and elsewhere a name word") -- a phrase is two 

2181 words and a comma part read by this shape is one; and 

2182 `given_name_abbreviations`, a given name written short (#789), 

2183 whose one reader is H2's shape, so anywhere else its word reads as 

2184 the unlisted word it is ('John Smith, JAS' keeps suffix 'JAS'); 

2185 and `given_names`, whose one reader is O6 (#959), for the same 

2186 reason ('Ana Pérez, LUIS' reads as with the list empty).""" 

2187 sets = lexicon._sets 

2188 for field in _LISTED_FIELDS: 

2189 if n in getattr(sets, field): 

2190 return True 

2191 return False 

2192 

2193 

2194_LISTED_FIELDS = tuple(f for f in _VOCAB_FIELDS 

2195 if f not in ("title_phrases", "titles_ambiguous", 

2196 "given_name_abbreviations", 

2197 "given_names")) 

2198 

2199 

2200#: The wordlists that claim a word as something OTHER than name text. 

2201#: `surnames` and `bound_given_names` are left out: they say a word IS 

2202#: a name word ('Kim', 'Abdul'), the opposite claim; and so is 

2203#: `titles_ambiguous`, a title that may be a given name (rules/H9), with 

2204#: `title_phrases`, whose two-word entries never match one word; and so 

2205#: is `given_name_abbreviations`, a given name written short (#789), left 

2206#: out of `_LISTED_FIELDS` above, with `given_names` (#959). 

2207_NON_NAME_FIELDS = tuple(f for f in _LISTED_FIELDS 

2208 if f not in ("surnames", "bound_given_names")) 

2209 

2210 

2211def is_capitals_word(text: str) -> bool: 

2212 """Whether TEXT is a name written in capitals, as rules/O9 reads 

2213 one: two or more letters in capitals ending the word, after any 

2214 lowercase prefix glued in front (`DUPONT`, `O'BRIEN`, `McDONALD`, 

2215 `d'ESTAING`), with nothing in it but letters, their combining marks 

2216 and `_NAME_JOINERS`. Single letters joined by a hyphen are 

2217 initials (`J-P`), and a word whose capitals are one letter is a 

2218 name in mixed case (`PhD`, `McD`). A combining mark is passed over 

2219 in the letter's run, so a capital typed as its base and an accent 

2220 (NFD) reads as its composed spelling does (#652). A 

2221 lowercase letter whose capital is not one character (`ß`) counts as 

2222 written in capitals, as `written_as_a_name` reads it.""" 

2223 word = text 

2224 # a joiner at either end is a quotation mark or a dash, not a name 

2225 # written with one inside it ('MBA', -AB) 

2226 if not word or word[0] in _NAME_JOINERS or word[-1] in _NAME_JOINERS: 

2227 return False 

2228 chunk = longest = 0 

2229 i = len(word) 

2230 while i: 

2231 i -= 1 

2232 ch = word[i] 

2233 if ch.isupper() or ch.islower() and len(ch.upper()) != 1: 

2234 chunk += 1 

2235 continue 

2236 if ch.islower(): 

2237 break # the prefix glued in front: McDONALD, d'ESTAING 

2238 if ch in _NAME_JOINERS: 

2239 longest = max(longest, chunk) 

2240 chunk = 0 

2241 continue 

2242 if unicodedata.category(ch) in ("Mn", "Mc", "Me"): 

2243 continue 

2244 return False # a full stop, slash, digit, bracket or caseless letter 

2245 # i is 0 where no lowercase prefix stopped the walk 

2246 if i and not all(c.isalpha() or c in _NAME_JOINERS 

2247 or unicodedata.category(c) in ("Mn", "Mc", "Me") 

2248 for c in word[:i]): 

2249 return False 

2250 return max(longest, chunk) >= 2 

2251 

2252 

2253def written_as_a_name(text: str) -> bool: 

2254 """Whether TEXT is written the way a name is written in mixed case: 

2255 it holds a capital (or titlecase letter) and its last LETTER is 

2256 lowercase -- #564's test for the name's case contrast (Derek). 

2257 'Smith', 'DiCaprio', 'IJzerman', 'al-Rashid', "d'Estaing", 

2258 'McDonald', 'Džokić' pass. A surname written in capitals fails 

2259 whatever is glued in front of it ("d'ESTAING", 'al-ASSAD', 

2260 'McDONALD', 'FitzGERALD', 'DeVITO', 'St-PIERRE'), and so do a lone 

2261 capital and a lowercase-only word. 

2262 

2263 The letter read is the last one that carries case evidence, not the 

2264 last character. The word is composed first (NFC), so a name typed 

2265 with decomposed accents reads as its composed spelling ('André' 

2266 ends in 'é', not in the combining accent). Passed over, as no 

2267 evidence of case: every non-letter ("Jones'", 'Smith2', 'Smith)'), 

2268 every caseless letter ("Jonesʼ" with U+02BC, 'Wafāʾ', 'Smith李'), 

2269 and a lowercase letter whose capital is not a single character 

2270 ('ß' -> 'SS', 'ĸ' with none): 'WEIß' and 'KAĸ' are written in 

2271 capitals, 'Weiß' is not. One call and no generator, so a word costs 

2272 one frame.""" 

2273 word = unicodedata.normalize("NFC", text) 

2274 i = len(word) 

2275 while i: 

2276 i -= 1 

2277 ch = word[i] 

2278 if not (ch.isupper() or ch.islower() or ch.istitle()): 

2279 continue # a non-letter or a caseless letter 

2280 upper = ch.upper() 

2281 if ch.islower() and (upper == ch or len(upper) != 1): 

2282 continue 

2283 # the capital is asked here, of the word that has a letter to 

2284 # read; one with none falls through below ('李', '2', 'ß') 

2285 return ch.islower() and text != text.lower() 

2286 return False 

2287 

2288 

2289def claimed_as_non_name(n: str, lexicon: Lexicon) -> bool: 

2290 """Whether a wordlist claims the folded word `n` as a title, 

2291 particle, connective, credential, generation, maiden marker or 

2292 honorific -- not name text. #564's `_comma._name_contrast` 

2293 asks it: such a word does not supply the name's case contrast. A 

2294 different question from `in_any_wordlist`'s, which a surname list 

2295 must also answer yes to.""" 

2296 sets = lexicon._sets 

2297 for field in _NON_NAME_FIELDS: 

2298 if n in getattr(sets, field): 

2299 return True 

2300 return False 

2301 

2302 

2303# The candidate test for a comma part read before classify 

2304# (rules/C4, decisions/S9): segment's C2 flag on a tail part. 

2305def ambiguous_class_candidate(text: str, lexicon: Lexicon, 

2306 policy: Policy) -> bool: 

2307 """Whether TEXT is a CANDIDATE for the ambiguous credential class 

2308 as segment's C2 flag asks it of a part past the second comma, 

2309 before classify has tagged anything (`_segment.py`'s `class_run`; 

2310 the comma's own decision, `_comma.decide`, reads classify's tags 

2311 instead, #613): the LISTED half (`ambiguous_class_member`, case-free) OR, where Policy 

2312 admits it, the SHAPE an unlisted dotted token wears 

2313 (`period_joined_vocab`'s third verdict, #516). 

2314 

2315 Case-free throughout, and the CAPS half of the class is 

2316 deliberately not here: its real site is `_comma.decide`, which 

2317 calls `caps_shape_candidate` directly because the caps shape needs 

2318 the name's contrast. A second route through here existed briefly, 

2319 behind an optional `one_case` parameter no production caller ever 

2320 passed -- segment had nothing to hand in at the single-token 

2321 test it then made -- so the branch 

2322 answered False for every name the library parsed and only the 

2323 unit tests reached it (review-round finding, #289/#516). A dead 

2324 second route is a place for the two to disagree, not a 

2325 convenience. 

2326 

2327 A period anywhere is the gate for even ASKING the shape question, 

2328 checked before the shape's own two calls: `period_joined_vocab` 

2329 already declines a period-free text, but a Python-level call is 

2330 not free and a comma name's post-comma part usually has no period 

2331 ("Smith, John") -- measured regression, #516 review round, fixed 

2332 by hoisting the same cheap substring test `ambiguous_class_member` 

2333 already makes for its own reason. Where a period IS present, 

2334 `suffix_as_written` runs only after `period_joined_vocab` says 

2335 "shape": a dotted whole-token match with no single-chunk 

2336 vocabulary hit of its own ('A.B.C.', via 'abc') would otherwise 

2337 read "shape" from this function's chunk-level view alone, 

2338 oblivious to the WHOLE-token match `suffix_as_written` already 

2339 settled -- the same precedence classify's own tag order gives it 

2340 (`vocab:suffix` is set before `period_joined_vocab` is even 

2341 consulted). 

2342 

2343 A LISTED member spelled with its periods is excluded from the 

2344 shape branch by the same test classify's own shape branch makes: 

2345 a caller who puts a dotted entry in `suffix_acronyms_ambiguous` 

2346 has said the word is a listed member of this class, and reading 

2347 it by shape instead loses the case lean the listing asks for 

2348 (review-round finding, #289/#516 -- `Jack A.B.` with 'a.b' listed). 

2349 It cannot change the answer for the shipped vocabulary, whose 

2350 ambiguous entries carry no period at all. 

2351 

2352 This function and classify's tag emission (`_tags_for`'s 

2353 `derived == "shape"` branch) still ask the SAME question twice, of 

2354 necessity: segment's C2 flag runs before `classify` and has no 

2355 tags to read yet, so the two stages cannot share the call. Kept from 

2356 drifting by 

2357 `test_classify.test_ambiguous_class_candidate_agrees_with_the_tag`, 

2358 which asks both of the same texts, rather than by a sentence 

2359 alone. 

2360 """ 

2361 if ambiguous_class_member(text, lexicon): 

2362 return True 

2363 if "." in text: 

2364 # `_normalize` stays behind the shape verdict, where it always 

2365 # was: it is a call, and a dotted post-comma token that is not 

2366 # acronym-shaped at all ('Jr.') must not pay for it. 

2367 if not (policy.unlisted_dotted_suffixes 

2368 and period_joined_vocab(text, lexicon) == "shape"): 

2369 return False 

2370 n = _normalize(text) 

2371 return (n not in lexicon._sets.suffix_acronyms_ambiguous 

2372 and not suffix_as_written(n, text, lexicon)) 

2373 return False 

2374 

2375 

2376# mechanisms.md#UNIT-PARTITION: "A rule that counts name words counts 

2377# those units, and takes each whole or not at all" -- C3's count before 

2378# a comma being the stated exception (`SURNAME_UNIT_TAGS`). The walk is shared 

2379# by readers that hold the facts in different forms: post_rules and 

2380# `_comma._whole_name` read classify's TAGS, while `name_word_count` 

2381# builds the same tag names from the vocabulary 

2382# (`surname_unit_tags`). One walk over tag sets, so the two cannot 

2383# disagree about where a unit ends (mechanisms.md#ONE-PREDICATE-PER- 

2384# QUESTION) -- only, at worst, about a token's facts, which 

2385# test_classify's agreement test pins. 

2386def unit_ends(tags: Sequence[Set[str]], chain: bool = True) -> list[int]: 

2387 """The END (one past the last index) of each unit of `tags`, in 

2388 order, partitioning `range(len(tags))`: one name word each, except 

2389 where another rule has already made several words one name -- a 

2390 particle and the words it chains (P2), a conjunction-joined run 

2391 (P3), a bound given-name word with the word it completes (P5), and 

2392 a pair P12 joined from its second word (#1072). Each element is the 

2393 tag set of one token, read for "particle", "conjunction", 

2394 "vocab:bound-given", "vocab:bound-second" and "vocab:suffix". 

2395 

2396 `chain` picks how far a particle reaches. True is P2's chain: the 

2397 particle run and every word after it up to the next stop ("van der 

2398 Berg Smith" is one unit). False is P1's fold reach: the particle 

2399 run and the ONE unit it attaches to, so "de Mesnil Jean" is two -- 

2400 the count rules/C3 needs before a comma, where under a 

2401 family-first order that part is family 'de Mesnil', given 'Jean' 

2402 (#575). 

2403 

2404 RECURSIVE, and that is the whole point: what a conjunction or a 

2405 bound given-name word joins is the next UNIT, not the next word. 

2406 Absorbing a single index instead strands a particle at the end of 

2407 the unit, severed from the words it chains -- "de la Vega y la 

2408 Vega" cut between `la` and `Vega`, reporting family 

2409 "de la Vega y la", which is the same defect as a bare particle 

2410 opening the given name, mirrored.""" 

2411 n = len(tags) 

2412 

2413 def end_of(i: int) -> int: 

2414 if "particle" in tags[i] and not chain: 

2415 j = i + 1 

2416 while j < n and "particle" in tags[j]: 

2417 j += 1 

2418 end = (end_of(j) if j < n and "conjunction" not in tags[j] 

2419 and "vocab:suffix" not in tags[j] else j) 

2420 elif "particle" in tags[i]: 

2421 j = i 

2422 while j + 1 < n and "particle" in tags[j + 1]: 

2423 j += 1 

2424 # ... then the words it joins, stopping where the next 

2425 # particle starts a group of its own, at a suffix word (the 

2426 # stop _group's chain uses), or at a conjunction, which the 

2427 # shared loop below joins to the whole unit after it rather 

2428 # than to the one word after it. 

2429 while (j + 1 < n 

2430 and "particle" not in tags[j + 1] 

2431 and "conjunction" not in tags[j + 1] 

2432 and "vocab:suffix" not in tags[j + 1]): 

2433 j += 1 

2434 end = j + 1 

2435 else: 

2436 end = i + 1 

2437 if "vocab:bound-given" in tags[i] and end < n: 

2438 end = end_of(end) 

2439 elif "vocab:bound-second" in tags[i] and end < n: 

2440 # a pair joined from its second word: the word and the 

2441 # one word after it (rules/P12, #1072) 

2442 end += 1 

2443 while end + 1 < n and "conjunction" in tags[end]: 

2444 end = end_of(end + 1) 

2445 return end 

2446 

2447 ends: list[int] = [] 

2448 i = 0 

2449 while i < n: 

2450 i = end_of(i) 

2451 ends.append(i) 

2452 return ends 

2453 

2454 

2455#: The facts rules/C3's count before a comma reads (#575): a 

2456#: particle starts a surname unit, and a suffix word stops it -- any 

2457#: suffix word, a wider stop than group's particle chain makes, which 

2458#: a suffix word ends only where a suffix run would start at it 

2459#: (decisions/P2, #1177). A word 

2460#: that is ALSO title vocabulary ('Freiherr', 'St') LEADING the part is 

2461#: not a particle here: in front of a name it reads as the title it 

2462#: also is (rules/H1), so 'Freiherr von Berg, PhD' keeps its title, 

2463#: while inside a surname it chains as P1 and P2 chain it ('de St 

2464#: Pierre' is one surname). A bound given-name head that is also a 

2465#: particle ('Abu') stays a particle: 'Abu Bakar, Ed' is a surname 

2466#: before the comma, as 2.0 through 2.3 read it. Neither of the other 

2467#: two joins `unit_ends` knows is read. A bound 

2468#: given-name pair builds a GIVEN name, and P5 gives up a family word 

2469#: where the name has no other ('abdul Salam' alone is given 'abdul', 

2470#: family 'Salam'), so before a comma it is not one surname. Whether 

2471#: P3 joins a single-letter connective depends on the words of the 

2472#: whole name -- 'Carod i Rovira, Josep' joins as four words where 

2473#: 'Ortega y Gasset' alone, three words, does not -- and the count is 

2474#: part of deciding what the whole name is, so a count taken before 

2475#: group could reach P3's answer only by copying P3. script_segment 

2476#: and `name_word_count` build these facts from the vocabulary 

2477#: (`surname_unit_tags`); `_comma._whole_name` derives them from 

2478#: classify's tags (`surname_unit_facts`), so the counts read one set 

2479#: of facts. 

2480SURNAME_UNIT_TAGS = frozenset({"particle", "vocab:suffix"}) 

2481_PARTICLE_ONLY = frozenset({"particle"}) 

2482_SUFFIX_ONLY = frozenset({"vocab:suffix"}) 

2483_NO_TAGS: frozenset[str] = frozenset() 

2484def surname_unit_facts(tags: Set[str], leading: bool) -> frozenset[str]: 

2485 """`SURNAME_UNIT_TAGS` for one token, from classify's tags: the 

2486 reading `_comma._whole_name`'s count before a comma takes. 

2487 `leading` is whether 

2488 the token opens the part.""" 

2489 particle = ("particle" in tags 

2490 and not (leading and "vocab:title" in tags)) 

2491 if "vocab:suffix" in tags: 

2492 return SURNAME_UNIT_TAGS if particle else _SUFFIX_ONLY 

2493 return _PARTICLE_ONLY if particle else _NO_TAGS 

2494 

2495 

2496def surname_unit_tags(text: str, lexicon: Lexicon, 

2497 leading: bool) -> frozenset[str]: 

2498 """`surname_unit_facts` for one token from the vocabulary alone -- 

2499 the vocabulary's view of classify's tags, for a count taken before 

2500 classify runs (script_segment's) or without its tags 

2501 (`name_word_count`), with 

2502 classify's own tests: particle and title membership, 

2503 `suffix_as_written`, and the period-joined derivation. 

2504 Kept from drifting by 

2505 test_classify.test_surname_unit_tags_agree_with_classify.""" 

2506 n = _normalize(text) 

2507 # classify's whole-token test, then its period-joined derivation 

2508 # for a token no whole-token title or suffix claimed ('JD.CPA'), 

2509 # asked only of a token with a period, which it needs 

2510 suffix = suffix_as_written(n, text, lexicon) or ( 

2511 "." in text and n not in lexicon._sets.titles 

2512 and period_joined_vocab(text, lexicon) == "suffix") 

2513 particle = n in lexicon._sets.particles and not ( 

2514 (leading and n in lexicon._sets.titles) or _spells_an_initial(n, text)) 

2515 if suffix: 

2516 return SURNAME_UNIT_TAGS if particle else _SUFFIX_ONLY 

2517 return _PARTICLE_ONLY if particle else _NO_TAGS 

2518 

2519 

2520#: The connective after a title that may be a given name which makes 

2521#: the two a title phrase, 'Dean of Students' (rules/H9). Coordinating 

2522#: connectives are not: 'Dean and Mary Smith' is two people. 

2523_PHRASE_LINKS = frozenset({"of"}) 

2524#: The connectives whose object a modifier after them is in, 'of the 

2525#: United States', 'The Grand Master'; 'and' joins two titles instead. 

2526_OBJECT_LINKS = frozenset({"of", "the"}) 

2527 

2528#: The article that is the phrase partner of a style that may be a 

2529#: given name, written short (rules/H9, #999): `The Hon`. 

2530_STYLE_ARTICLES = frozenset({"the"}) 

2531 

2532 

2533# rules/H9: "a word no listed phrase holds is a title only behind a 

2534# style or a modifier, or before `of`" -- whether the word heads a title 

2535# of itself, asked of the phrases `attaches` compiled rather than of a 

2536# property of its own 

2537def in_a_title_phrase(text: str, lexicon: Lexicon) -> bool: 

2538 """Whether a phrase of `lexicon._sets.title_phrases` that classify can 

2539 read holds `text`.""" 

2540 return _normalize(text) in _phrase_words( 

2541 lexicon._sets.title_phrases, lexicon._sets.titles, lexicon._sets.titles_ambiguous) 

2542 

2543 

2544@functools.lru_cache(maxsize=16) 

2545def _phrase_words(phrases: frozenset[str], titles: frozenset[str], 

2546 contested: frozenset[str]) -> frozenset[str]: 

2547 """The words of the phrases classify can read: two words, each a 

2548 title or a title that may be a given name, as its pair test asks. 

2549 A phrase it never consults makes no word report.""" 

2550 listed = titles | contested 

2551 pairs = (p.split(" ") for p in phrases) 

2552 return frozenset(w for ws in pairs 

2553 if len(ws) == 2 and all(w in listed for w in ws) 

2554 for w in ws) 

2555 

2556 

2557# rules/H9: "the word is a title only inside a title phrase, and 

2558# elsewhere a name word" -- both halves, the partners of a title that may 

2559# be a given name and of a modifier at the head of the name, each its 

2560# bullet's (decisions/H9 #752) 

2561def title_readings(texts: Sequence[str], folded: Sequence[str], 

2562 lexicon: Lexicon, *, head: bool, 

2563 titled: Sequence[bool] | None = None) -> list[bool]: 

2564 """Which of these words, one part of the name in order, read as 

2565 title words. Where none of them is a title that may be a given name 

2566 or a modifier, the listed titles answer alone, which every caller 

2567 asks first, in C, so that a name with neither pays no frame. 

2568 

2569 A word of `titles_ambiguous` that is not also in `titles` (where a 

2570 caller listing it makes it a title everywhere) is a title only 

2571 beside a partner: a 

2572 modifier, a style, or a title it stands behind in `title_phrases`, 

2573 before it, and for a style of `title_abbreviations` the article 

2574 'the' before it ('The Hon' under a Chinese choice); or 'of', or a title it stands in front of in 

2575 `title_phrases`, after it. A salutation is never one, nor any other 

2576 title before it ('Mr Dean Smith'), nor a title after it that it 

2577 does not attach to ('SMITH, DEAN MR.', a given name and the 

2578 salutation a donor list writes after it). Its neighbours are asked 

2579 as LISTED, so 'Vice Dean' reads 'Vice' as the partner of 'Dean' 

2580 whatever the modifier test below makes of 'Vice', save a word before 

2581 it that is itself a title that may be a given name, which is a 

2582 partner only where its own phrase made it a title ('Grace Dean 

2583 Smith' reads 'Grace' as the given name, and 'Dean' with it). 

2584 

2585 Where `head` is true -- the part before the first comma -- a word 

2586 of `title_modifiers` is a title only with a head title behind it in 

2587 its run of titles: any title that is not a modifier, or a word H2's 

2588 shape reads as one, before 'of' ('Mother Superior of the Convent'), 

2589 behind a title that attaches to it in `title_phrases` ('Princess 

2590 Royal', #913), or in the object of 'of' or 'the' there (decision 10 of 

2591 decisions/vocabulary-model). Only the leading run is the head: a 

2592 modifier outside it is read as listed, one ending the name being 

2593 H5's. A 

2594 word in both sets takes the modifier test in every part, that run 

2595 being its phrase ('Lau, Wing Kai' reads 'Wing' as the given name). 

2596 After a comma any other modifier is read as listed: a part there 

2597 that is a lone title word is the person's role ('John Smith, 

2598 Resident'), and reading it as a name would reverse the name 

2599 (decisions/H9). 

2600 

2601 `texts` are the words as written, for the shape test; `folded` 

2602 their `_normalize`d forms; `titled` which of them a caller already 

2603 reads as titles, where that is more than `titles` lists (classify's 

2604 period-joined `Lt.Gov.`), else membership in `titles`. Only a word 

2605 of the two sets is ever read out of the title.""" 

2606 contested = lexicon._sets.titles_ambiguous 

2607 modifiers = lexicon._sets.title_modifiers 

2608 titles = lexicon._sets.titles 

2609 # a word in titles is a title wherever it stands, whatever else it 

2610 # is listed as; one of titles_ambiguous alone is listed as a title 

2611 # to its neighbours and read by its phrase 

2612 reading = [n in titles or n in contested for n in folded] 

2613 if titled is not None: 

2614 reading = [r or t for r, t in zip(reading, titled)] 

2615 listed = list(reading) 

2616 phrases = lexicon._sets.title_phrases 

2617 last = len(folded) - 1 

2618 for i, n in enumerate(folded): 

2619 if n in titles or n not in contested or n in modifiers: 

2620 continue 

2621 prev = folded[i - 1] if i else None 

2622 nxt = folded[i + 1] if i < last else None 

2623 reading[i] = bool( 

2624 # the word before as it was READ, left to right: a title that 

2625 # may be a given name and stands in no phrase is no partner 

2626 # ('Grace Dean Smith') 

2627 (prev is not None and reading[i - 1] 

2628 and (prev in modifiers or prev in lexicon._sets.title_styles 

2629 or f"{prev} {n}" in phrases)) 

2630 # rules/H9: "a style that may be a given name, written short, 

2631 # has its phrase partner in the article before it" -- 'The 

2632 # Hon' under a Chinese choice (decisions/H9, #999) 

2633 or (prev in _STYLE_ARTICLES and n in lexicon._sets.title_styles 

2634 and n in lexicon._sets.title_abbreviations 

2635 and prev in lexicon._sets.conjunctions) 

2636 or (nxt is not None 

2637 and ((nxt in _PHRASE_LINKS and nxt in lexicon._sets.conjunctions) 

2638 or (listed[i + 1] and f"{n} {nxt}" in phrases)))) 

2639 # left to right, whether the run so far has passed 'of' or 'the': a 

2640 # modifier after it is in the object of a phrase ('President of the 

2641 # United States', 'the Queen's Bench'), which no head need follow. A 

2642 # coordinating connective opens no object: 'Mr. and Mrs. Wing Lau' 

2643 # is two salutations and a given name 

2644 linked = [False] * len(folded) 

2645 conjunctions = lexicon._sets.conjunctions 

2646 for i in range(1, len(folded)): 

2647 if reading[i - 1] or folded[i - 1] in conjunctions: 

2648 linked[i] = linked[i - 1] or folded[i - 1] in _OBJECT_LINKS 

2649 # the head of the name is its LEADING run of titles and connectives: 

2650 # a modifier ending the name is H5's trailing run, read as listed, 

2651 # save one that may be a given name, which the loop below reads 

2652 # wherever it stands 

2653 lead = 0 

2654 if head: 

2655 while lead < len(folded) and (reading[lead] or folded[lead] in conjunctions 

2656 or is_title_shaped(texts[lead], lexicon)): 

2657 lead += 1 

2658 # right to left, so each modifier knows whether a head title stands 

2659 # behind it before the run is broken; a connective carries the run 

2660 behind = False 

2661 for i in range(last, -1, -1): 

2662 n = folded[i] 

2663 if (n in modifiers and reading[i] 

2664 and ((head and i < lead) or (n in contested and n not in titles))): 

2665 reading[i] = behind or linked[i] or ( 

2666 i < last and folded[i + 1] in _PHRASE_LINKS 

2667 and folded[i + 1] in conjunctions) or ( 

2668 # a title before it that attaches to it ('Princess Royal') 

2669 i > 0 and reading[i - 1] 

2670 and f"{folded[i - 1]} {n}" in phrases) 

2671 behind = reading[i] 

2672 elif reading[i] or (head and is_title_shaped(texts[i], lexicon)): 

2673 behind = True 

2674 elif n not in conjunctions: 

2675 behind = False 

2676 return reading 

2677 

2678 

2679def name_word_count(texts: Sequence[str], lexicon: Lexicon, 

2680 policy: Policy, letters_one_case: bool | None = None, 

2681 members: Set[int] = frozenset()) -> int: 

2682 """How many of these texts are NAME words -- not suffix 

2683 vocabulary, not title vocabulary, nor a numeral the trailing fork 

2684 reads as the generation ending the name words (rules/C3). 

2685 

2686 rules/C4's count for the ambiguous class, and it is of names 

2687 rather than of words because 'Smith Jr., MA' is two tokens and one 

2688 name: counting tokens there flips the structure and hands the 

2689 family to `given`, which no reading of that string wants 

2690 (decisions/S6). The suffix half asks the POLICY-selected 

2691 predicate, the same one is_wholly_suffix asks, so the two agree 

2692 about what a suffix word is; the title half asks BOTH the listed 

2693 lookup and H2's shape test (`is_title_shaped`) -- a bare 

2694 `lexicon._sets.titles` lookup here read 'Xyz.' as a name word where the 

2695 leading peel reads it as a title, and that divergence is recorded 

2696 once, at `is_title_shaped` itself 

2697 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

2698 

2699 It counts UNITS holding a name word, not tokens (#575, 

2700 mechanisms.md#UNIT-PARTITION): a particle chain (P2) builds one 

2701 family name, so 'De La Cruz' is one name word and 'De La Cruz, Ed' 

2702 reads as 'Royce, Ed' does. Why the other two joins are not read 

2703 here: `SURNAME_UNIT_TAGS`. 

2704 

2705 `letters_one_case` is `is_wholly_suffix`'s, for the same reason, 

2706 and the case fact the generation fork reads (`ParseState.one_case`). 

2707 `members` holds the positions of split credentials' members 

2708 (classify's tag), each half a credential rather than a name, so 

2709 one opening the part stays no name word, as `_comma._whole_name` 

2710 reads it. 

2711 """ 

2712 lenient = policy.lenient_comma_suffixes 

2713 

2714 # One pass: each token's name-word verdict, and whether any token 

2715 # is a particle. With none, every token is a unit of its own and 

2716 # the count is a sum, so the commonest comma names never build the 

2717 # units -- and pay no frame the token loop did not already pay. 

2718 names: list[bool] = [] 

2719 suffixes: list[bool] = [] 

2720 has_particle = False 

2721 lead: int | None = None 

2722 lead_suffix = False 

2723 # map, not a comprehension, which is a frame of its own on 3.11 

2724 folded = list(map(_normalize, texts)) 

2725 # rules/H10: "the run reads as that title where a title the run 

2726 # keeps stands behind it" -- the run read as the title it spells, so 

2727 # the title test and H9's phrase test below see it. Unlike classify's 

2728 # fold, which runs only where the name already holds a word H9 

2729 # reads, this one always runs, so a run alone brings the phrase test 

2730 # in. The set test first, C-level, so a dotted word that spells no 

2731 # marked title pays no frame 

2732 dotted: set[int] = set() 

2733 for i, n in enumerate(folded): 

2734 if ("." in n and n.replace(".", "") in lexicon._sets.dotted_titles 

2735 and is_dotted_title(texts[i], n, lexicon)): 

2736 folded[i] = n.replace(".", "") 

2737 dotted.add(i) 

2738 # rules/H9: "the word is a title only inside a title phrase" -- the 

2739 # part before the comma is the head of the name, read as classify 

2740 # reads it 

2741 titled = (None if lexicon._sets.titles_ambiguous.isdisjoint(folded) 

2742 and lexicon._sets.title_modifiers.isdisjoint(folded) 

2743 else title_readings(texts, folded, lexicon, head=True)) 

2744 for i, n in enumerate(folded): 

2745 text = texts[i] 

2746 title = n in lexicon._sets.titles if titled is None else titled[i] 

2747 if title and i in dotted: 

2748 # a title only opening the part (behind any titles), and only 

2749 # with a title, listed or by H2's shape, behind it and a word 

2750 # of any kind behind that: H6 leaves the part's last word to 

2751 # the family, so a title ending the part is not kept and the 

2752 # run is given back ('U.S. Senator, Ed'); H3's floor is not 

2753 # modelled here (decisions/H10) 

2754 nxt = i + 1 

2755 title = (lead is None and nxt < len(folded) 

2756 and ((folded[nxt] in lexicon._sets.titles 

2757 if titled is None else titled[nxt]) 

2758 or is_title_shaped(texts[nxt], lexicon)) 

2759 and nxt + 1 < len(folded)) 

2760 if n in lexicon._sets.particles: 

2761 has_particle = True 

2762 suffix = (is_suffix_lenient(text, lexicon) if lenient 

2763 else is_suffix_strict(text, lexicon, letters_one_case)) 

2764 name = not (suffix or title or is_title_shaped(text, lexicon)) 

2765 # the opening word behind any titles; the shape test asked again 

2766 # only of a suffix word there, so a run of them pays no frame 

2767 if lead is None and (name or suffix and not title 

2768 and not is_title_shaped(text, lexicon)): 

2769 lead = i 

2770 lead_suffix = not name and i not in members 

2771 names.append(name) 

2772 suffixes.append(suffix) 

2773 # rules/C3: "A suffix word opening the part is a name word to the 

2774 # count where a name word follows it" -- opening it behind its 

2775 # titles, which stay no name word, this count being of names 

2776 # (rules/C4) 

2777 if lead_suffix and lead is not None and any(names[lead + 1:]): 

2778 names[lead] = True 

2779 # rules/C3: "a numeral ending the part, or standing before the 

2780 # listed suffix words it ends with, that the trailing fork reads as the 

2781 # generation is no name word", as a listed one is not 

2782 # -- the suffix words stepped over as `_comma._whole_name` steps 

2783 # over them, a dual of the title and suffix vocabulary included, 

2784 # and a title that is no suffix word stopping both 

2785 e = len(texts) - 1 

2786 while e > 0 and suffixes[e]: 

2787 e -= 1 

2788 # the numeral's shape asked in C first, as group's count asks it, so 

2789 # a part ending in a plain word pays no frame 

2790 if (e > 0 and names[e] 

2791 and _ROMAN.match(texts[e].rstrip(".")) is not None 

2792 and ends_in_a_generation(texts[e - 1:e + 1], letters_one_case)): 

2793 names[e] = False 

2794 if not has_particle: 

2795 return sum(names) 

2796 count = 0 

2797 start = 0 

2798 for end in unit_ends([surname_unit_tags(t, lexicon, i == 0) 

2799 for i, t in enumerate(texts)], 

2800 chain=False): 

2801 if any(names[start:end]): 

2802 count += 1 

2803 start = end 

2804 return count 

2805 

2806 

2807def is_wholly_suffix(texts: Sequence[str], lexicon: Lexicon, 

2808 policy: Policy, one_case: bool | None = None, 

2809 letters_one_case: bool | None = None, 

2810 strict: bool = False) -> bool: 

2811 """Every token in a RUN counts as a suffix -- C1's suffix test of 

2812 a run, shared by `_comma.decide`, segment's C2 flag on a tail part 

2813 and the peel (#319). 

2814 

2815 NOT the plural of _script_segment._is_post_nominal, which asks 

2816 is_suffix_strict per token. This asks the POLICY-selected predicate 

2817 (lenient by default), plus period_joined_vocab, delimiter 

2818 transparency and the Ph./D. merge. 'V.' is the input that tells 

2819 them apart: it satisfies this predicate but is not a post-nominal 

2820 -- and reading one for the other IS the #319 bug. 

2821 

2822 An EMPTY run is False, not vacuously True: v1's suffix-comma 

2823 detection fails on an empty parts[1] ('John Smith,, MD' is a 

2824 family-comma parse). The 'wholly' idiom agrees -- _script_matcher's 

2825 whole=True requires non-empty too -- which is why the name is that 

2826 one rather than all_suffixes, where Python's all([]) would promise 

2827 the opposite. 

2828 

2829 An adjacent Ph./D. pair counts as ONE unit (v1's fix_phd extracted 

2830 the credential pre-parse, so 'Smith, Ph. D.' read as suffix-comma): 

2831 `split_pair`'s "suffix" answer, which group's merge and 

2832 `_comma._pieces` read too. Its "split" answer ('Pharm D') does not 

2833 count here: that pair is a member of the ambiguous class, which no 

2834 run test takes by itself, as it takes no bare 'Ma' (rules/C4's 

2835 count reads it instead). 

2836 

2837 `one_case` is ParseState.one_case, and it admits the LEAN: a bare 

2838 ambiguous acronym written in capitals inside a mixed-case name is 

2839 a credential here, so 'Steven Hardman, MD, DO, DDS' reads its 

2840 third segment as the credential run it is (#289). None -- the 

2841 default, and what every caller with no state to ask has -- reads 

2842 as no lean and is this predicate's behavior in every release 

2843 before 2.4. 

2844 

2845 `letters_one_case` is the same fact asked a different question, 

2846 and the two are kept apart because a caller that wants no lean 

2847 still wants the letters read by T4: under 

2848 `lenient_comma_suffixes=False` the strict test vetoes an 

2849 initial, and in a name written in one case a bare lowercase 

2850 letter is one ('john smith, v' reads as 'JOHN SMITH, V', #727). 

2851 The lenient test takes a suffix word whatever its shape, so the 

2852 default never reads it. 

2853 

2854 Neither Policy.unlisted_dotted_suffixes NOR 

2855 Policy.unlisted_caps_suffixes reaches this predicate: admitting a 

2856 by-shape member here unconditionally (an earlier version of this 

2857 docstring described exactly that, for the dotted half alone) 

2858 bypassed both the lean AND the NAME-word count, and combined with 

2859 C1's then TOKEN-count disjunct in segment (deleted in #613, when 

2860 the decision moved to `_comma.decide`) it flipped 

2861 'Smith Jr., A.B.' to given 'Smith', suffix 'Jr., A.B.' with a 

2862 self-contradicting report ("holds 1 name words, so it is read as 

2863 a credential run") -- proved by mutation testing to be otherwise 

2864 unreached: nothing but this predicate's own two unit tests 

2865 depended on it, and 'John Smith, X.Y.Z.' flipped correctly through 

2866 the NAME-word count alone (#516 review round). Neither by-shape 

2867 class, dotted or caps, reaches the comma form through this 

2868 predicate at all -- only through classify's shape tags and 

2869 `_comma.decide`'s caps test (#613). 

2870 

2871 A delimiter core glued to one word ('MD;', ';PhD') leaves the word 

2872 read by the test it would get without the core (D15, rules/C10), 

2873 so 'MD;' counts where 'MD' does. `strict` asks the strict token 

2874 test whatever the policy says: `_comma.decide` passes it behind a 

2875 head that is not a whole name, where C8 reads 'Smith, V MD' with 

2876 the initial veto, so that 'Smith, V; MD' reads as its space twin. 

2877 """ 

2878 if not texts: 

2879 return False 

2880 lenient = policy.lenient_comma_suffixes and not strict 

2881 # v1 expand_suffix_delimiter parity (#206): a configured delimiter 

2882 # is TRANSPARENT in the all-suffix tests -- v1 split the part string 

2883 # on the delimiter before checking, so the delimiter never counted; 

2884 # the built-in cores are transparent the same way (rules/C10) 

2885 cores = delimiter_cores(policy.extra_suffix_delimiters) 

2886 inner = glued_cores(policy.extra_suffix_delimiters) 

2887 

2888 def counts_as_suffix(text: str) -> bool: 

2889 if (one_case is not None 

2890 and ambiguous_class_member(text, lexicon) 

2891 and ambiguous_lean(text, one_case, lexicon_cue( 

2892 _normalize(text), lexicon)) == "credential"): 

2893 return True 

2894 if ((is_suffix_lenient(text, lexicon) if lenient 

2895 else is_suffix_strict(text, lexicon, letters_one_case)) 

2896 or period_joined_vocab(text, lexicon) == "suffix"): 

2897 return True 

2898 # the split only where a core stands in the word: the built-in 

2899 # ';' makes `inner` non-empty for every policy, and a call per 

2900 # word would be a frame on every name word a run test asks 

2901 for core in inner: 

2902 if core in text: 

2903 stem = glued_stem(text, inner) 

2904 if stem is not None: 

2905 return counts_as_suffix(stem) 

2906 return splits_into_suffixes(text, inner, lexicon) 

2907 return False 

2908 

2909 merged = list(texts) 

2910 k = 0 

2911 while k < len(merged) - 1: 

2912 if (SPLIT_PAIR_OPENS.fullmatch(merged[k]) 

2913 and split_pair(merged[k], merged[k + 1], lexicon) 

2914 == "suffix"): 

2915 merged[k:k + 2] = ["phd"] 

2916 else: 

2917 k += 1 

2918 return all(t in cores or counts_as_suffix(t) for t in merged) 

2919 

2920 

2921# The two derived views of a marker vocabulary, cached per-vocabulary 

2922# on _script_segment._longest_entry's precedent -- same function shape 

2923# (a scalar derived from a vocabulary frozenset), same key space, and 

2924# its reasoning for maxsize=16 carries over verbatim: a process holds 

2925# the default vocabulary plus one per constructed pack parser, so 16 

2926# bounds many-lexicon churn without ever evicting in normal use. 

2927# (NOT _extract._delimiter_chars' precedent, which these once cited: 

2928# that one is consulted once per parse, so it says nothing about a 

2929# lookup on the per-token path.) Keying on the frozenset costs a 

2930# cached hash, not a sweep of its contents. 

2931@functools.lru_cache(maxsize=16) 

2932def _longest_marker(markers: frozenset[str]) -> int: 

2933 """How many words the longest entry of `markers` spans -- the 

2934 lookahead bound, computed from the vocabulary rather than fixed at a 

2935 literal so a caller's four-word entry works and an all-single-word 

2936 set leaves the common path at one lookup. Entries are stored 

2937 space-joined with single separators, so the space count IS the word 

2938 count.""" 

2939 return max((entry.count(" ") + 1 for entry in markers), default=0) 

2940 

2941 

2942@functools.lru_cache(maxsize=16) 

2943def _marker_heads(markers: frozenset[str]) -> frozenset[str]: 

2944 """The first word of every entry -- the set a run can possibly open 

2945 with. Entries are already stored per-word folded, so an entry's 

2946 first word is the same fold the lookup builds.""" 

2947 return frozenset(entry.split(" ", 1)[0] for entry in markers) 

2948 

2949 

2950def maiden_marker_head(n: str, markers: frozenset[str]) -> bool: 

2951 """Could a maiden marker run START here? `n` is _normalize(word), 

2952 passed in so callers fold once -- suffix_as_written's shape exactly 

2953 ("`n` is `_normalize(text)`, passed in so callers normalize once"), 

2954 and with no raw-text sibling for the same reason it has none: every 

2955 caller is on the per-token path and has the fold in hand already. 

2956 

2957 A SUPERSET test. True means only that some entry opens with this 

2958 word, never that a run matches -- maiden_marker_run is the answer, 

2959 and it calls this function, so the two cannot drift. Exported 

2960 because a caller scanning a whole token stream needs to know 

2961 whether assembling a candidate sequence is worth doing at all, and 

2962 for almost every token it is not: _classify's pass would otherwise 

2963 walk structural boundaries once per token to build a lookahead the 

2964 predicate discards on this very test. 

2965 """ 

2966 return n in _marker_heads(markers) 

2967 

2968 

2969def maiden_marker_run(words: Sequence[str], markers: frozenset[str]) -> int: 

2970 """How many of `words` a maiden marker claims, longest first; 0 for 

2971 none. 

2972 

2973 Phrases are stored space-joined and per-word normalized (_title_key's 

2974 storage rule), so the key is rebuilt the same way here -- normalizing 

2975 the joined phrase instead would leave interior periods. 

2976 

2977 `words` must be words that stand TOGETHER -- one clause's, or one 

2978 segment's. This answers only what the vocabulary says about the 

2979 sequence it is handed; whether a sequence is a sequence is the 

2980 caller's, and classify's contiguity rule is where that is decided 

2981 for the token stream. 

2982 

2983 Longest first, so a caller configuring both 'geb' and 'geb von' gets 

2984 the phrase where it matches and the bare word everywhere else. The 

2985 one answer to "does a marker start here, and where does it end": the 

2986 stages that can call it do (classify over token texts, extract over 

2987 a clause's whitespace words), and the stage that runs after classify 

2988 reads the tags classify recorded instead 

2989 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

2990 """ 

2991 # Fast path first: no entry opens with this word, so no length can 

2992 # match. It cannot hide a match -- every key the loop builds opens 

2993 # with _normalize(words[0]) unless that word folds away, and a 

2994 # folded-away first word fails the n-word test below for every 

2995 # n > 1 and is not a stored entry for n == 1. 

2996 if not words: 

2997 return 0 

2998 head = _normalize(words[0]) 

2999 if not maiden_marker_head(head, markers): 

3000 return 0 

3001 cap = min(len(words), _longest_marker(markers)) 

3002 # Fold each word ONCE, then key from a prefix. _title_key(words[:n]) 

3003 # per candidate length re-folds the whole prefix every time, which 

3004 # is quadratic in cap and makes a one-word hit cost more than a 

3005 # two-word one -- the longest key is always built and discarded 

3006 # first, and all but one shipped entry is a single word. The join 

3007 # below IS _title_key's body over pre-folded words (per-word fold, 

3008 # empties dropped, space-joined); test_vocab pins that the two 

3009 # agree, since this is a copy of a fold whose definition lives in 

3010 # _lexicon. 

3011 folded = [head] + [_normalize(w) for w in words[1:cap]] 

3012 for n in range(cap, 0, -1): 

3013 key = " ".join(filter(None, folded[:n])) 

3014 # a word that folds away is DROPPED from the key, so 'née' 

3015 # followed by a lone '.' would key as 'née' and a one-word 

3016 # marker would claim the period as part of its run. n words in, 

3017 # n words out: anything else is not this key's n-word phrase. 

3018 if key.count(" ") == n - 1 and key in markers: 

3019 return n 

3020 return 0 

3021 

3022 

3023 

3024# rules/M3: "a marker followed by a comma is no marker" 

3025def comma_follows_marker(word: str) -> bool: 

3026 """Whether `word`, the one standing after a marker run inside a 

3027 delimited clause, opens with a comma -- standing alone (' , ') or 

3028 glued to the name after it (' ,Jones'). A comma glued to the marker 

3029 itself ('née,') needs no test: that word is no marker to begin with, 

3030 the vocabulary storing no comma (and an alias marker's, which classify 

3031 keeps on the word for that reason, rules/N4). The one predicate for 

3032 extract's M3 and N4 tests over whitespace words and group's M1 and 

3033 N4 drops over tokens, which 

3034 since #653 hold the same comma 

3035 (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

3036 

3037 The comma need not be the word's first character, only the first 

3038 that is a comma or a letter or digit. A whitespace word can open 

3039 with what the tokenizer drops or divides at -- a bidi mark, an 

3040 emoji, a nakaguro -- so '\u200f, Jones' is a comma-led WORD only 

3041 past its mark, while the token group asks about is ',' already; 

3042 reading past the rest makes the two sites agree by construction 

3043 (#653's second review).""" 

3044 for ch in word: 

3045 if ch in COMMA_CHARS: 

3046 return True 

3047 if ch.isalnum(): 

3048 return False 

3049 return False 

3050 

3051 

3052def tag_marker_runs(tokens: Sequence[WorkToken], comma_offsets: Sequence[int], 

3053 markers: frozenset[str], 

3054 folded: Sequence[str] | None = None) -> dict[int, str]: 

3055 """Which tokens are maiden marker runs: index -> "vocab:maiden-marker" 

3056 for a run's head, "vocab:maiden-marker-cont" for the rest. 

3057 

3058 Returns the decision rather than rewriting the tokens: a caller 

3059 that writes tags into the one pass that builds them (classify) 

3060 consults this map rather than deciding a run twice, so a marker 

3061 token is never replaced twice; a caller that never writes tags at 

3062 all (own_words) reads the same map for its span instead. 

3063 

3064 Moved here from classify (#289/#516) so a caller outside classify 

3065 -- _pieces.own_words, when it has no marker map yet -- can build 

3066 the SAME map classify would, rather than approximating it with a 

3067 text-only head test. `_pieces.py` may import only _state and 

3068 _vocab (tests/v2/test_layering.py), so the one shared function 

3069 both sites call has to live here, in the layer both can reach. 

3070 

3071 `folded` is _normalize per token; classify has already built it 

3072 for the vocabulary-tag pass and hands it over so this pass costs 

3073 no second fold, and a caller with only tokens (own_words' self- 

3074 built path) omits it and pays the fold here instead -- paid only 

3075 on that path, never on classify's, so the reference name's frame 

3076 count is unchanged (#289/#516). 

3077 

3078 The one sequence pass in this stage, and it has to be one: a marker 

3079 entry may be a PHRASE whose words are not markers individually 

3080 ('z', 'domu'), so no per-token membership test can find it. 

3081 Left to right, longest first at each position, then skip past what 

3082 the run claimed -- a second marker cannot start inside the first. 

3083 

3084 This is where the tag is DECIDED for the stages that read it 

3085 afterwards. group runs later and asks its questions of these tags 

3086 rather than re-deriving the run (the recorded-answer half of 

3087 mechanisms.md#ONE-PREDICATE-PER-QUESTION); extract runs EARLIER, 

3088 before tokens exist, so it calls the predicate itself over the 

3089 clause's whitespace words. 

3090 

3091 A tagged run is structurally contiguous, and the test is 

3092 one-directional: a role change IS a clause edge, so no run spans 

3093 one, but not every clause edge is a role change -- two ADJACENT 

3094 clauses of the same role are indistinguishable here, and 

3095 'Jane (z) (domu) Jones' does tag a run across them. Both consumers 

3096 refuse that run for reasons of their own (the piece walk never sees 

3097 role-bearing tokens at all; the clause drop is scoped to one 

3098 clause's span), so no reading depends on it today, and the claim 

3099 this pass can honestly make is the weaker one. What it does 

3100 guarantee is what _group._marker_run_pieces needs: a run inside the 

3101 MAIN stream stays inside one segment. Without it this pass walked 

3102 the whole span-sorted stream while group walked one segment -- 

3103 _segment keeps only role-less tokens and buckets them by the commas 

3104 before them -- so a run half inside a bracketed clause was tagged 

3105 whole and consumed as a proper PREFIX of itself, and 

3106 'Anna z (domu) Nowak' read family 'Anna', maiden 'Nowak': the bare 

3107 preposition eating the name, which is the exact damage the phrase 

3108 entry exists to prevent. Refusing to tag such a run is the fix; 

3109 truncating it instead would hand M2 the same wrong prefix one word 

3110 shorter. 

3111 """ 

3112 # the lookahead the vocabulary actually needs; 0 for an empty set, 

3113 # which skips the pass entirely 

3114 cap = _longest_marker(markers) 

3115 if not cap: 

3116 return {} 

3117 if folded is None: 

3118 folded = [_normalize(t.text) for t in tokens] 

3119 n_tokens = len(tokens) 

3120 # Deferred, not computed up front: only the contiguity walk reads 

3121 # it, only a phrase vocabulary runs that walk, and only at a token 

3122 # that opens an entry -- so a single-word vocabulary, and a 

3123 # phrase vocabulary over a name holding no marker, never pay the 

3124 # sweep at all. 

3125 buckets: list[int] | None = None 

3126 tags: dict[int, str] = {} 

3127 i = 0 

3128 while i < n_tokens: 

3129 # The predicate's own head test first, over the fold the caller 

3130 # already has: almost no token opens any entry, and for those 

3131 # there is nothing to assemble. Same function maiden_marker_run 

3132 # consults, so a token skipped here is one it would refuse. 

3133 if not maiden_marker_head(folded[i], markers): 

3134 i += 1 

3135 continue 

3136 # Bound the lookahead at the first structural boundary, so the 

3137 # predicate is asked over the words that could form one run and 

3138 # answers longest-first WITHIN them -- a two-word entry refused 

3139 # at a clause edge still leaves a one-word entry starting there 

3140 # free to match. 

3141 limit = 1 

3142 if cap > 1: 

3143 if buckets is None: 

3144 buckets = [comma_bucket(t.span.start, comma_offsets) 

3145 for t in tokens] 

3146 role, bucket = tokens[i].role, buckets[i] 

3147 while (limit < cap and i + limit < n_tokens 

3148 and tokens[i + limit].role is role 

3149 and buckets[i + limit] == bucket): 

3150 limit += 1 

3151 run = maiden_marker_run( 

3152 [tokens[k].text for k in range(i, i + limit)], markers) 

3153 if not run: 

3154 i += 1 

3155 continue 

3156 tags[i] = "vocab:maiden-marker" 

3157 for k in range(i + 1, i + run): 

3158 tags[k] = "vocab:maiden-marker-cont" 

3159 i += run 

3160 return tags 

3161 

3162 

3163def _normalized_for_script(text: str) -> str | None: 

3164 """The guard AND the two normalizations single_script and 

3165 effective_script's license path both need, single-sourced so they 

3166 cannot drift: trailing full stops are dropped (FULL_STOPS, #323), 

3167 then None for the two shapes neither ever classifies (nothing 

3168 left, and the common all-ASCII Latin token -- skipped before 

3169 normalizing, since ASCII is already NFC and every _SCRIPT_RANGES 

3170 entry is non-ASCII regardless), else an NFC-normalized copy. 

3171 

3172 Trailing stops, not raw: a period glued to a script-written token 

3173 ('양.', '太郎.') is not a character of any script, so classifying 

3174 raw text handed the token no script at all, and three readers 

3175 spent that None -- the surname site stepped past the family name 

3176 onto the given name ('양. 지훈' cut 지훈 in half), the order rule 

3177 fell back to positional ('양 지훈.' lost family-first), and the 

3178 segmenter's neighbour precondition missed a writer-drawn boundary 

3179 ('山田太郎 田中.' consulted the segmenter on 山田太郎 as if it stood 

3180 alone). The East Asian scripts this classifies (_policy's 

3181 _EAST_ASIAN_SCRIPTS, the four East Asian rows of _policy._SCRIPT_PROPERTIES, #320) have no 

3182 initials and no period abbreviations, so a stop on such a token 

3183 carries no information about the word; on a Cyrillic word it is an 

3184 initial's stop (`Б.`), dropped all the same, deliberately: the 

3185 classification keys only a declared Cyrillic order (#1237), under 

3186 which an initial is a word of the name in its script; ASCII text is stripped too, 

3187 but the guard below returns None for it regardless, so 'Smith.' 

3188 never classifies. TRAILING only, matching the surname site's own 

3189 rstrip in _script_segment (the same arithmetic, not a shared 

3190 gate -- this fold decides only whether the surname site, the order 

3191 rule and the segmenter ever see the token): a leading stop is not 

3192 a shape any script writes before a name word, and HIDING such a 

3193 token from those three readers -- no script, so no surname site, 

3194 which is what the tree before #323 did -- is safer than admitting 

3195 it. Admitted, '.김민준' classifies as hangul, becomes a surname 

3196 site, is declined by the head match (which rstrips) and falls 

3197 through to a configured segmenter, which answering offset 1 

3198 divides it into the stop and the name. The peel is not gated by 

3199 this fold; its own rstrip carries a leading-stop token, see 

3200 _script_segment. The vocabulary fold alone reads BOTH edges 

3201 (_lexicon._normalize): '.씨' is still the honorific, and a lookup 

3202 divides nothing. 

3203 

3204 NFC, not raw: NFD input decomposes precomposed katakana onto a 

3205 base character plus a COMBINING mark (U+3099/U+309A, which sit in 

3206 the HIRAGANA block, not katakana's), so classifying raw NFD text 

3207 can hand a pure-katakana token the kana license by accident. 

3208 Decomposed hangul is conjoining jamo, which HANGUL holds, so the 

3209 fold no longer decides a hangul token (decisions/nfd-shapes, 

3210 #1087). 

3211 

3212 Voicing marks, last: NFC composes a mark only where a precomposed 

3213 kana exists (カ + U+3099 is ガ), so ア + U+3099, ン + U+3099 and 

3214 every spacing mark (U+309B/U+309C) survive it, and all four marks 

3215 sit in the HIRAGANA block. A mark voices the kana it follows and 

3216 belongs to neither syllabary, so each one standing after a kana is 

3217 deleted from the copy (_drop_kana_voicing_marks) and the token 

3218 takes its base's script: ア゙イ is katakana, not kana-licensed 

3219 Japanese (#596). A mark after anything else stays, and stays in 

3220 the hiragana block, as it always has. Classification-only and 

3221 read-only, like the rest: the 

3222 returned copy is never what gets tokenized, so token text and 

3223 spans stay exactly what the caller wrote. 

3224 

3225 Vocabulary MATCHING composes NFC too, since #322 

3226 (_lexicon._normalize folds every lookup and every stored entry the 

3227 same way), so an NFD suffix word reaches its NFC entry. What stays 

3228 raw is SEGMENTATION -- the surname site's direct membership test 

3229 and the peel's tail slice index the token's own text -- where NFD 

3230 degrades to no-split, never to a wrong split (decisions/W1, 

3231 the 2026-07-29 ja amendment). 

3232 """ 

3233 text = text.rstrip(FULL_STOPS) 

3234 if not text or text.isascii(): 

3235 return None 

3236 composed = unicodedata.normalize("NFC", text) 

3237 if _VOICING_MARKS.isdisjoint(composed): 

3238 return composed 

3239 return _drop_kana_voicing_marks(composed) 

3240 

3241 

3242def _classify(normalized: str) -> Script | None: 

3243 """The FIRST _SCRIPT_MATCHERS entry covering all of `normalized` 

3244 (already NFC, via _normalized_for_script), else None. Shared by 

3245 both public classifiers so each of them normalizes exactly once. 

3246 The East Asian scripts first, then CYRILLIC, asked only of a word 

3247 that opens with a Cyrillic letter.""" 

3248 for script, matcher in _EAST_ASIAN_MATCHERS: 

3249 if matcher(normalized): 

3250 return script 

3251 if (normalized[0] in _CYRILLIC_LETTERS 

3252 and _SCRIPT_MATCHERS[Script.CYRILLIC](normalized)): 

3253 return Script.CYRILLIC 

3254 return None 

3255 

3256 

3257def single_script(text: str) -> Script | None: 

3258 """The one Script whose ranges cover EVERY char of `text`, else 

3259 None (mixed-script text has no well-defined convention to apply; 

3260 the caller falls back to the positional default). Classifies an 

3261 NFC-normalized copy of `text` -- see _normalized_for_script. 

3262 Callers wanting the kana-mixed license (a kanji+kana composite 

3263 resolving to HIRAGANA) want effective_script, not this function.""" 

3264 normalized = _normalized_for_script(text) 

3265 if normalized is None: 

3266 return None 

3267 return _classify(normalized) 

3268 

3269 

3270def effective_script(text: str) -> Script | None: 

3271 """single_script, extended by the kana license (#272 amendment): 

3272 a MIXED token wholly within Han∪hiragana∪katakana is Japanese -- 

3273 it necessarily contains kana (pure Han is not mixed), cannot be 

3274 Chinese, and is not a foreign transcription (those are 

3275 katakana-only: マイケル has no kanji, but さくらエミ -- hiragana 

3276 plus katakana -- is kana-only AND licensed) -- and resolves to the 

3277 HIRAGANA carrier entry. Pure-katakana stays KATAKANA 

3278 (single_script's answer): a lone katakana token may be a 

3279 transcribed foreign name or a Japanese reading, and the script 

3280 cannot say which, so nothing defaults on it. Halfwidth kana is 

3281 katakana by the table (#594), so 山田タロウ is licensed too. Last, a 

3282 Cyrillic word with a hyphen or an apostrophe inside it is CYRILLIC 

3283 (#1237), which only a declared Cyrillic order reads.""" 

3284 # None for both shapes _wholly_ja could never match anyway (empty 

3285 # text, or all-ASCII text): real work, not a leftover "if text" 

3286 # guard, since the ASCII case is one a bare emptiness check would 

3287 # let through. The single normalized copy then serves both the 

3288 # single-script answer and the license below. 

3289 normalized = _normalized_for_script(text) 

3290 if normalized is None: 

3291 return None 

3292 script = _classify(normalized) 

3293 if script is not None: 

3294 return script 

3295 if _wholly_ja(normalized): 

3296 return Script.HIRAGANA 

3297 # a Cyrillic word with a hyphen or an apostrophe inside it (#1237); 

3298 # translate is C-level, so a token with no joiner costs no frame 

3299 joined = normalized.translate(_DROP_NAME_JOINERS) 

3300 if (joined != normalized and normalized[0] in _CYRILLIC_LETTERS 

3301 and normalized[-1] not in _NAME_JOINERS 

3302 and _SCRIPT_MATCHERS[Script.CYRILLIC](joined)): 

3303 return Script.CYRILLIC 

3304 return None 

3305 

3306 

3307def resolve_script_set(scripts: Iterable[Script]) -> Script | None: 

3308 """Generalizes effective_script's kana license from one token's 

3309 CHARACTERS to a whole name's PIECES (#272): `scripts` is the 

3310 effective_script of every name token, already resolved 

3311 individually -- '高橋' (Han) and 'みなみ' (Hiragana) are two 

3312 separately single-script pieces (split by a space, not mixed 

3313 within one token), but together are exactly the repertoire 

3314 effective_script licenses inside a single token (高橋みなみ). A 

3315 single distinct script is returned as-is (the ordinary case, 

3316 including a lone wholly-katakana name, which callers key with no 

3317 table entry); more than one collapses to the HIRAGANA carrier 

3318 when confined to Han/Hiragana/Katakana, the same set 

3319 effective_script's license tests; any other mix (Han+Hangul, or 

3320 no scripts at all -- an empty `scripts`) returns None -- the 

3321 caller's cue to fall back to the positional default, exactly like 

3322 effective_script's own None. A non-None result reports what was 

3323 FOUND, not that a license fired: callers wanting to know whether 

3324 the kana license specifically was the reason must compare the 

3325 result against a specific Script (e.g. `is Script.HIRAGANA`), not 

3326 just its truthiness -- a lone wholly-Han name also returns 

3327 non-None here, licensing nothing.""" 

3328 found = frozenset(scripts) 

3329 if len(found) <= 1: 

3330 return next(iter(found), None) 

3331 if found.issubset(_JA_SCRIPTS): 

3332 return Script.HIRAGANA 

3333 return None 

3334 

3335 

3336# -- the reading a decision did not take (Ambiguity.alternative, #752 

3337# phase 2m). Each report names it from what its own site knows: the 

3338# word's tags say which reading the vocabulary or a shape gave it, and 

3339# the emitter says which field (decisions/vocabulary-model, 2026-10-26) 

3340 

3341#: Tags that say the vocabulary declares the word a name as well as a 

3342#: word of another category: the derived markers (decisions/ 

3343#: vocabulary-model, 2026-10-25), and a given name written short. The 

3344#: ambiguous class's tag is also written by SHAPE (rules/S9), which 

3345#: `name_reading` reads off the shape tag beside it. 

3346_DECLARED_NAME_TAGS = frozenset({ 

3347 AMBIGUOUS_ACRONYM_TAG, AMBIGUOUS_WORD_TAG, "vocab:particle-ambiguous", 

3348 TITLE_AMBIGUOUS_TAG, GIVEN_ABBREVIATION_TAG}) 

3349 

3350 

3351def suffix_reading(token: WorkToken) -> PendingReading: 

3352 """The suffix reading of a word a decision read as a name: a 

3353 generation or agnomen by its listed word, a numeral by its shape 

3354 unless listed, another listed suffix word by its vocabulary kind, 

3355 and otherwise a credential, listed or shaped.""" 

3356 kind, source = suffix_kind(token.text, token.tags) 

3357 return PendingReading(kind, source, Role.SUFFIX) 

3358 

3359 

3360def suffix_kind(text: str, 

3361 tags: Set[str]) -> tuple[ReadingKind, ReadingSource]: 

3362 """`suffix_reading`'s kind and source, which assemble also asks of 

3363 a word the parse read as a suffix (`Token.reading`), so the 

3364 reading taken and the reading not taken are named by one 

3365 predicate.""" 

3366 if AGNOMEN_TAG in tags: 

3367 return ReadingKind.AGNOMEN, ReadingSource.VOCABULARY 

3368 if CREDENTIAL_WORD_TAG in tags: 

3369 return ReadingKind.CREDENTIAL, ReadingSource.VOCABULARY 

3370 if AMBIGUOUS_WORD_TAG in tags or GENERATION_WORD_TAG in tags: 

3371 return ReadingKind.GENERATION, ReadingSource.VOCABULARY 

3372 if _ROMAN.match(text.rstrip(".")) is not None: 

3373 listed = "vocab:suffix" in tags or "vocab:suffix-word" in tags 

3374 return (ReadingKind.GENERATION, 

3375 ReadingSource.VOCABULARY if listed else ReadingSource.SHAPE) 

3376 if "vocab:suffix-word" in tags: 

3377 return (ReadingKind.HONORIFIC if HONORIFIC_WORD_TAG in tags 

3378 else ReadingKind.POST_NOMINAL), ReadingSource.VOCABULARY 

3379 return (ReadingKind.CREDENTIAL, 

3380 ReadingSource.SHAPE if SHAPE_ACRONYM_TAG in tags 

3381 else ReadingSource.VOCABULARY) 

3382 

3383 

3384def name_reading(token: WorkToken, role: Role | Deferred) -> PendingReading: 

3385 """The name reading of a word a decision read as something else, 

3386 landing in `role`: an initial where the word is one letter or 

3387 initial-shaped, otherwise a name word, declared by the vocabulary 

3388 where a derived marker says so and standing by position where 

3389 nothing does.""" 

3390 text = token.text 

3391 # C-level for an ASCII word, so a report pays no frame for the test 

3392 if (len(text.rstrip(".")) == 1 or _INITIAL.fullmatch(text) 

3393 if text.isascii() 

3394 else composed_len(text.rstrip(".")) == 1 

3395 or is_initial_shaped(text)): 

3396 return PendingReading(ReadingKind.INITIAL, ReadingSource.SHAPE, role) 

3397 return PendingReading(ReadingKind.NAME, name_source(token.tags), role) 

3398 

3399 

3400def name_source(tags: Set[str]) -> ReadingSource: 

3401 """Why a word reads as a name word: declared by the vocabulary 

3402 where a derived marker says so, and by position where nothing 

3403 does. `name_reading`'s source, which assemble also asks of a word 

3404 the parse read as a name (`Token.reading`).""" 

3405 # rules/O9: "the capitals settle the field" -- read by the word's 

3406 # shape, the reading taken being the family its capitals named 

3407 if CAPITALS_FAMILY_TAG in tags: 

3408 return ReadingSource.SHAPE 

3409 # classify writes the ambiguous class's tag on a word admitted by 

3410 # its shape too, so the shape tag says no list declared it 

3411 if (not tags.isdisjoint(_DECLARED_NAME_TAGS) 

3412 and SHAPE_ACRONYM_TAG not in tags): 

3413 return ReadingSource.DECLARED 

3414 return ReadingSource.POSITION 

3415 

3416 

3417#: The particle reading of a word read as a name: a particle joins the 

3418#: words after it, the last group reading as the family (rules/P2). 

3419PARTICLE_READING = PendingReading(ReadingKind.PARTICLE, 

3420 ReadingSource.VOCABULARY, Role.FAMILY) 

3421#: The same for a patronymic particle (rules/R9): its particle reading 

3422#: is a patronymic, joining the parent's name after it. 

3423PATRONYMIC_READING = PendingReading(ReadingKind.PATRONYMIC, 

3424 ReadingSource.VOCABULARY, Role.FAMILY) 

3425 

3426 

3427def particle_reading(tags: frozenset[str]) -> PendingReading: 

3428 """The particle reading of a word read as something else, by the 

3429 kind classify tagged it with: a patronymic particle's is 

3430 `PATRONYMIC_READING`, any other's `PARTICLE_READING`.""" 

3431 return PATRONYMIC_READING if PATRONYMIC_TAG in tags else PARTICLE_READING 

3432 

3433 

3434#: The title reading of a word read as a name. 

3435TITLE_READING = PendingReading(ReadingKind.TITLE, ReadingSource.VOCABULARY, 

3436 Role.TITLE)