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

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

220 statements  

1"""Stage: classify. 

2 

3Consumes: tokens, segments (the part a title phrase or a split 

4credential's pair is read within), extracted (whether a delimited 

5clause holds a word with a comma on it, rules/S1), comma_offsets (with token roles, the two halves of 

6the structural-boundary test the marker pass applies -- see 

7_vocab.tag_marker_runs), and one_case where an earlier stage recorded 

8it -- segment writes it lazily where C2's flag on a part past the 

9second comma asks for it (#289/#516, #613), so this read is the 

10fallback for every other name. 

11Produces: tokens with vocabulary tags added (text/span/role unchanged), 

12plus ambiguities (CONJUNCTION_OR_INITIAL) and 

13one_case -- whether the name's own words are written in one case, 

14recorded for the later stages that read it (#289/#516) and left alone 

15where an earlier stage already asked. 

16Reads: every Lexicon vocabulary field except given_names, which only 

17post_rules and assemble read (rules/O6) -- surnames and 

18honorific_tails, which script_segment consumes upstream, only through 

19helpers: the caps shape's unlisted test (`_vocab.in_any_wordlist`) 

20reads both, and `_vocab.period_joined_credential` honorific_tails; 

21and the kinds 

22of its suffix words and particles (Lexicon's generation_words, 

23credential_words, honorific_words and patronymic_particles, internal 

24sets, 3.0) and the alias markers (alias_markers, rules/N4, 3.2) and the 

25suffix words whose Title case leans to the name 

26(title_case_name_words, rules/S6, #1039) and the 

27titles written short (title_abbreviations, #999) and the names a 

28community gives every member (shared_names) and the given names 

29written behind a particle (particle_given_names, #704) and the 

30two-word given names a bound word completes into (bound_phrases, 

31#694) and the bound words that complete with any plain name word 

32(bound_completes_any, #1464) and the words a 

33pair writes second and joins from, and the pairs those list 

34(bound_seconds, bound_second_phrases, bound_seconds_listed, #1072) 

35and the titles a 

36run of single letters may spell (dotted_titles, rules/H10, #490) and 

37the saint particles a word glued at its full stop is cut behind (saint_particles, through 

38`_vocab.glued_saint_cut`); and, since 

392.4, Policy.unlisted_dotted_suffixes and Policy.unlisted_caps_suffixes, 

40which decide whether an UNLISTED dotted or all-caps token joins the 

41ambiguous credential class by SHAPE (#516) -- the all-caps half here 

42only under CapsSuffixes.EVERYWHERE, the default's part after a comma 

43being tagged by `_comma.decide` when group binds it (#613); and 

44Policy.extra_suffix_delimiters, with the built-in semicolon 

45(_vocab.glued_cores), so a word after the first comma with a 

46delimiter glued to it is tagged as the word without it (rules/C10). 

47is_initial also consults 

48the _policy module's _SCRIPT_PROPERTIES table. It is named apart from the 

49fields above because it is not CONFIGURATION -- no Lexicon or Policy 

50carries it and no caller can change it -- and not because it decides 

51nothing: the tags this stage writes do vary by it ('씨.' is not tagged 

52`initial`, which is the whole of #320). 

53 

54Tags emitted -- stable (API): "particle", "conjunction", "initial"; 

55namespaced (unstable), kept on the published token: "vocab:title", 

56"vocab:given-title", "vocab:after-given-title", 

57"vocab:title-ambiguous", "vocab:dotted-title" (a run of single letters 

58spelling a title the lexicon marks `dotted`, rules/H10, #490), 

59"vocab:suffix", "vocab:suffix-word", "vocab:suffix-ambiguous", 

60"vocab:suffix-word-ambiguous", "vocab:agnomen", "vocab:title-case-name" 

61(a suffix word whose Title case leans to the name, rules/S6), 

62"vocab:particle-ambiguous", "vocab:bound-given", 

63"vocab:given-abbreviation", "vocab:maiden-marker", 

64"vocab:maiden-marker-cont" and "vocab:alias-marker" (rules/N4; a 

65marker group drops leaves no token; one read as a word keeps its tag); namespaced, read by the later stages and dropped 

66by assemble (`_assemble._KIND_TAGS`): "vocab:generation-word", 

67"vocab:credential-word", "vocab:honorific-word" and "vocab:patronymic", 

68Token.reading carrying the kind out, "vocab:trailing-title", 

69"vocab:joined-title" and "vocab:chain-title", which mark no kind, 

70"vocab:shared-name" (which rules/P10, O6 and O7 read), 

71"vocab:particle-given" (which P10 and O6 read) and "vocab:bound-phrase" 

72(on a bound word and the word after it being a listed pair, which P12 

73joins and O6 counts once, #694); in a namespace of its own, 

74"shape:acronym"; and in another, "split:credential" and 

75"split:member", written on the first word of a credential split across 

76a space (`_vocab.split_pair`) to name the piece the pair merges into: 

77the Ph./D. pair's unambiguous suffix where the lexicon lists `phd` as 

78an unambiguous credential, or any other pair's member of the ambiguous 

79class (rules/S12). 

80"vocab:maiden-marker" tags the HEAD of a maiden marker, which is a 

81whole marker whenever the marker is one word; the continuation tag 

82carries the rest of a PHRASE marker ("z domu"), so a site asking 

83"does a marker start here" reads the same tag it always did and a site 

84asking "where does it end" walks the continuations. 

85"vocab:suffix" means "counts as a suffix as written": unambiguous 

86suffix vocabulary, or an ambiguous acronym written with periods -- 

87at the TAG level 'M.A.' gets "vocab:suffix" while 'Ma' gets only 

88"vocab:suffix-ambiguous"; what assign then does with a trailing 

89ambiguous tag is rules S4 to S7 (the words-to-spare guard, the 

90case, the company) and their Accepted consequences. 

91The initial veto is assign's job, not classify's: 'V' carries both 

92"vocab:suffix" and "initial". 

93"shape:acronym" is the one tag in the shape: namespace and it records 

94WHERE a class claim came from rather than what the vocabulary holds: 

95an unlisted token the writing makes credential-shaped. It rides 

96beside "vocab:suffix-ambiguous" where a Policy switch admits the 

97token to that class, and stands alone where the switch is off, which 

98is what lets the fork be reported without being taken. 

99""" 

100from __future__ import annotations 

101 

102import re 

103import unicodedata 

104 

105from nameparser._lexicon import _normalize, _spells_an_initial 

106from nameparser._policy import CapsSuffixes 

107from nameparser._pipeline._state import ( 

108 AGNOMEN_TAG, AMBIGUOUS_ACRONYM_TAG, AMBIGUOUS_WORD_TAG, COMMA_STRIP, CREDENTIAL_WORD_TAG, 

109 GENERATION_WORD_TAG, GIVEN_ABBREVIATION_TAG, HONORIFIC_WORD_TAG, 

110 ALIAS_MARKER_TAG, BOUND_PHRASE_TAG, BOUND_SECOND_TAG, PARTICLE_GIVEN_TAG, PATRONYMIC_TAG, SHAPE_ACRONYM_TAG, SHARED_NAME_TAG, SPLIT_CREDENTIAL_TAG, SPLIT_MEMBER_TAG, TITLE_AMBIGUOUS_TAG, 

111 TITLE_CASE_NAME_TAG, 

112 CHAIN_TITLE_TAG, DOTTED_TITLE_TAG, JOINED_TITLE_TAG, TRAILING_TITLE_TAG, 

113 ParseState, 

114 Deferred, PendingAmbiguity, PendingReading, 

115 WorkToken, copy_with, 

116) 

117from nameparser._types import AmbiguityKind, ReadingKind, ReadingSource 

118from nameparser._pipeline._vocab import ( 

119 BUILTIN_GLUED_DELIMITERS, SPLIT_CHUNK, SPLIT_PAIR_OPENS, _INITIAL, _JOINED_WORD, 

120 _TRAILING_TITLE_SHAPE, caps_shape_candidate, 

121 composed_len, glued_cores, glued_stem, is_cased_paired_initials, 

122 is_dotted_title, is_initial, is_one_case, 

123 period_joined_title, period_joined_vocab, 

124 split_pair, 

125 suffix_as_written, tag_marker_runs, title_readings, 

126) 

127from nameparser._pipeline._pieces import own_words 

128 

129 

130#: The tag H9 leaves on a contested title it read as a name word. 

131_CONTESTED_TAGS = frozenset({TITLE_AMBIGUOUS_TAG}) 

132#: What rules/P12 writes on a bound word heading a pair, and on the word 

133#: before a second it joins from. 

134_BOUND_PHRASE_TAGS = frozenset({BOUND_PHRASE_TAG}) 

135_BOUND_SECOND_TAGS = frozenset({BOUND_PHRASE_TAG, BOUND_SECOND_TAG}) 

136#: A letter (a decomposed accent's base included): a search, not a 

137#: loop over the word, so the test costs no frame. 

138_HAS_LETTER = re.compile(r"[^\W\d_]") 

139 

140 

141# rules/S2: "a trailing word of the suffix vocabulary reads as a 

142# suffix — generational forms and credential acronyms alike" -- and 

143# rules/S3: "an ambiguous acronym written with its periods, one after 

144# each letter or one after each of two or more letter chunks, counts 

145# unambiguously; a single trailing period is the abbreviation shape 

146# any word can wear and does not" -- and rules/S4: "a 

147# bare ambiguous acronym is consumed only when the name has words to 

148# spare" -- the tags those readings weigh: "vocab:suffix" on a word that 

149# counts as written, the ambiguous class's tag on one the words-to-spare 

150# guard weighs (decisions/S2, decisions/S3, decisions/S4, decisions/S9 

151# (#516)) 

152def _tags_for(token: WorkToken, n: str, state: ParseState, 

153 marker_tag: str | None, one_case_own: bool, 

154 one_case: bool, letter_one_case: bool) -> frozenset[str]: 

155 """`n` is _normalize(token.text), folded once by the caller and 

156 shared with the marker pass; `marker_tag` is what that pass decided 

157 for this token, or None. The marker DECISION is entirely 

158 `_vocab.tag_marker_runs`'; only the writing happens here, so the 

159 two tokens of a phrase are built once rather than replaced twice. 

160 

161 `one_case_own` is true when the name's OWN words are written in one 

162 case AND this token is one of the name's own words -- a maiden clause 

163 and any delimited (nickname) content are not, so the fork never 

164 reads them either (rules/P3): a clause's words are not the 

165 name's own words, and appending one must not change how THIS token 

166 reads. 

167 

168 `one_case` is the own words' fact alone, asked of every token 

169 whatever its position -- P3's own-words span is not this question's 

170 business. #516's caps branch reads 

171 THIS, not `one_case_own`: a maiden clause's own words are outside 

172 `one_case_own`'s span by construction (`i < clause_at` fails for 

173 every one of them), so a token past the clause cut reads 

174 `one_case_own` as False even where the own words are written in one 

175 case, and a clause's word in capitals would read as a credential in 

176 a name written in them ('XYZ' in 'JOHN SMITH NEE JONES XYZ' under 

177 CapsSuffixes.EVERYWHERE; decisions/S9 (#516)). `single_letter_connective` below 

178 keeps `one_case_own`: that fork is genuinely about the OWN-WORDS 

179 span, and reads a clause's word as no evidence on purpose. 

180 

181 `letter_one_case` is rules/T4's question for THIS token: the 

182 own-words fact for one of the name's own words, and for a word 

183 outside them -- a clause's, or past a declined marker -- the fact 

184 about the WHOLE name, since the own words' case says nothing 

185 about how the clause beside them was written: 'y' in 'MARIA 

186 GARCIA NEE LOPEZ y FERNANDEZ' is a lower-case letter among 

187 capitals, which T4 reads as no initial (decisions/T4 (#723)).""" 

188 lex = state.lexicon 

189 tags = set(token.tags) 

190 if marker_tag is not None: 

191 tags.add(marker_tag) 

192 if n in lex._sets.titles: 

193 tags.add("vocab:title") 

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

195 # inside it chains without a final one" -- marked here, where 

196 # the listing is known whole; a period, since a hyphen alone 

197 # joins whole words as often as abbreviations ('co-founder') 

198 # (decisions/H5 (#1104)) 

199 if "." in n and _JOINED_WORD.match(n): 

200 tags.add(JOINED_TITLE_TAG) 

201 # rules/H10: "a run of single letters joined by full stops whose 

202 # spelling without them is a title the vocabulary marks as written 

203 # that way" -- the tag; whether a title the run keeps follows it is 

204 # for the title runs to ask (`_pieces.leading_titles`, and H6's in 

205 # assign). The stop and set tests first, C-level, so a word with no 

206 # interior stop, or one spelling no marked title, pays no frame 

207 # (decisions/H10 (#490)). 

208 elif ("." in n and n.replace(".", "") in lex._sets.dotted_titles 

209 and is_dotted_title(token.text, n, lex)): 

210 tags.add(DOTTED_TITLE_TAG) 

211 if n in lex._sets.given_name_titles: 

212 tags.add("vocab:given-title") 

213 # rules/H5: "a title that may be a given name is title vocabulary 

214 # there where its title reading is written short" -- marked here, 

215 # where the sets are at hand, so the chain reads a tag (decisions/H5 

216 # (#999)) 

217 if (n in lex._sets.title_abbreviations 

218 and n in lex._sets.titles_ambiguous): 

219 tags.add(TRAILING_TITLE_TAG) 

220 # rules/H8: "the word joins the title field" -- tagged only where the 

221 # word is a title too, so an entry outside `titles` is inert 

222 # (decisions/H8 (#835)) 

223 if n in lex._sets.after_given_titles and n in lex._sets.titles: 

224 tags.add("vocab:after-given-title") 

225 if suffix_as_written(n, token.text, lex): 

226 tags.add("vocab:suffix") 

227 if n in lex._sets.suffix_words_ambiguous: 

228 # rules/S11: "it reads as the suffix only where the name has words 

229 # to spare" -- the ambiguous class's tag, so every site 

230 # that weighs a member weighs this one, and the cue tags that 

231 # tell `_pieces.listed_lean` how its writing leans (decisions/S11) 

232 tags.add(AMBIGUOUS_ACRONYM_TAG) 

233 tags.add(AMBIGUOUS_WORD_TAG) 

234 if n in lex._sets.title_case_name_words: 

235 tags.add(TITLE_CASE_NAME_TAG) 

236 if n in lex._sets.agnomens: 

237 tags.add(AGNOMEN_TAG) 

238 # rules/R8: "The kind of a word listed as a suffix word is the 

239 # lexicon's" -- a gated credential (`kc`) reads as a 

240 # credential, not the generation the class otherwise holds 

241 # (decisions/S11 (#965)) 

242 elif n in lex._sets.credential_words: 

243 tags.add(CREDENTIAL_WORD_TAG) 

244 elif n in lex._sets.suffix_words: 

245 tags.add("vocab:suffix-word") 

246 # rules/R8: "The kind of a word listed as a suffix word is the 

247 # lexicon's" -- read here, from the word as this stage reads it 

248 # (decisions/R8, #326; #754, 4i-b) 

249 if n in lex._sets.generation_words: 

250 tags.add(GENERATION_WORD_TAG) 

251 elif n in lex._sets.credential_words: 

252 tags.add(CREDENTIAL_WORD_TAG) 

253 elif n in lex._sets.honorific_words: 

254 tags.add(HONORIFIC_WORD_TAG) 

255 if n in lex._sets.suffix_acronyms_ambiguous: 

256 tags.add(AMBIGUOUS_ACRONYM_TAG) 

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

258 # initial and not a particle" -- both particle tags, so 'Ó.' is 

259 # neither half of the vocabulary (decisions/P7) 

260 if n in lex._sets.particles and not _spells_an_initial(n, token.text): 

261 tags.add("particle") 

262 if n in lex._sets.particles_ambiguous: 

263 tags.add("vocab:particle-ambiguous") 

264 # rules/R9: "a particle the lexicon holds as a patronymic" -- its 

265 # kind, read here as a suffix word's is (decisions/R9, #754) 

266 if n in lex._sets.patronymic_particles: 

267 tags.add(PATRONYMIC_TAG) 

268 # rules/N4: "a recognized alias marker" -- group reads the tag 

269 # (decisions/N4 (#1164)) 

270 if n in lex._sets.alias_markers: 

271 tags.add(ALIAS_MARKER_TAG) 

272 # rules/P8: "a single-letter connective reads as an initial 

273 # where the writing says so: written as a bare Latin capital in a 

274 # name that is not written wholly in one case, or — in a name 

275 # written wholly in one case, where nothing says so — where the 

276 # letter is one the vocabulary marks as reading both ways" 

277 # (#383/#479; history: decisions/P8) 

278 # one letter as the writer sees it: a decomposed 'й' is two code 

279 # points (#665), so non-ASCII text is counted composed, after the 

280 # C-level tests have declined everything else 

281 single_letter_connective = (n in lex._sets.conjunctions 

282 and token.text.upper() != token.text.lower() 

283 and (len(token.text) == 1 

284 or not token.text.isascii() 

285 and composed_len(token.text) == 1)) 

286 if single_letter_connective and one_case_own: 

287 # No case evidence, so the vocabulary decides. No namespaced 

288 # tag beside it: the emitted ambiguity IS the record of the 

289 # decision (mechanisms.md#MARK-DONT-STRIP is satisfied by the 

290 # report) -- mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE says 

291 # emit where the branch is taken, not where an ambiguous tag 

292 # sits, and a vocab: tag records MEMBERSHIP, not the branch 

293 # taken, so it is the wrong shape of record here. 

294 if n in lex._sets.conjunctions_ambiguous: 

295 tags.add("initial") 

296 else: 

297 # a bare capital y joins here, where mixed case vetoes it 

298 tags.add("conjunction") 

299 else: 

300 # the mixed-case rule, unchanged. v1's is_conjunction excludes 

301 # initials: 'e.' in 'john e. smith' is a middle initial, not 

302 # the Spanish conjunction 'e' 

303 # rules/T4: "in a name written wholly in one case, which says 

304 # nothing about any letter in it, a bare letter is an initial 

305 # wherever its capital would be" -- the tag, so every reader 

306 # after classify reads 'j' as it reads 'J'; a reader that asks 

307 # the word's text rather than its tag takes the same fact as an 

308 # argument (decisions/T4 (#723, #727), decisions/S10 (#721)). A clause's letter 

309 # asks the whole name's case (`letter_one_case`, docstring). The 

310 # capital is asked of the bare pattern at C level, no frame per 

311 # one-letter word, and needs no script test: no capital 

312 # `_INITIAL` matches is in a script without initials. 'é' and 'ж' 

313 # stay as they were, their capitals being no initial either 

314 initial = is_initial(token.text) or ( 

315 letter_one_case and len(token.text) == 1 

316 and _INITIAL.fullmatch(token.text.upper()) is not None) 

317 if n in lex._sets.conjunctions and not initial: 

318 tags.add("conjunction") 

319 if initial: 

320 tags.add("initial") 

321 if n in lex._sets.bound_given_names: 

322 tags.add("vocab:bound-given") 

323 # rules/H2: "an abbreviation the vocabulary reads as a given name 

324 # written short is that given name" -- the reading H2's shape test 

325 # weighs (`_pieces.is_leading_title`); a membership, so any spelling 

326 # carries it. Read too by rules/C13's given-name Except 

327 # (`_comma._given_name_written_short`) and rules/S8's one-case 

328 # clause (`_pieces.short_given_name_in_one_case`) (decisions/H2 

329 # (#789), decisions/S8 (#1394)) 

330 if n in lex._sets.given_name_abbreviations: 

331 tags.add(GIVEN_ABBREVIATION_TAG) 

332 # rules/O6, O7 and P10 read this: a name a community gives every 

333 # member is neither taken nor completed by the two-name switches, 

334 # nor completed by P10's particle phrase (decisions/P10 (#704)) 

335 if n in lex._sets.shared_names: 

336 tags.add(SHARED_NAME_TAG) 

337 # rules/P10 and O6 read this: a given name written behind a particle 

338 # completes the given name it follows (decisions/P10 (#704)) 

339 if n in lex._sets.particle_given_names: 

340 tags.add(PARTICLE_GIVEN_TAG) 

341 # maiden markers are NOT tagged here: an entry may be a phrase whose 

342 # words are not markers on their own, and this function sees one 

343 # token with no neighbours. `_vocab.tag_marker_runs` does the whole 

344 # field, single words included, so there is one place that decides 

345 # it (mechanisms.md#ONE-PREDICATE-PER-QUESTION). 

346 # The block a WHOLE-TOKEN vocabulary match skips, and four 

347 # readings inside it, in precedence order. The first two are v1's 

348 # period-joined derivation (parse_pieces): a token with a period 

349 # not at the end, ANY of whose period chunks is a title, is a 

350 # title as a whole ('Lt.Gov.', and by the ANY rule 'Mr.Smith'); 

351 # else a suffix where EVERY chunk counts ('JD.CPA', #1131). Title wins 

352 # (v1's continue). The third and fourth are 2.4's by-shape halves 

353 # (#516; rules/S9: "joins the ambiguous class (S4) by SHAPE, in 

354 # the positions each shape is admitted") and reach only a 

355 # token NO vocabulary claimed: a dotted token of two or more 

356 # alphabetic chunks, and -- where its switch is on -- an unlisted 

357 # all-caps word. They are an `elif` chain 

358 # with the dotted one first, so a dotted token never reaches the 

359 # caps test and the two shapes stay disjoint. 

360 # 

361 # Both by-shape branches carry SHAPE_ACRONYM_TAG BESIDE the 

362 # membership tag rather than instead of it: `vocab:` records 

363 # membership (the roster above) and the peel reads membership, 

364 # while the shape tag records that the claim came from the 

365 # WRITING. The dotted branch writes it even with its switch off, 

366 # which is what lets a declined fork be reported without being 

367 # taken. `role is None` guards both: a token already carrying a 

368 # role is delimited content, decided by extract's escape and never 

369 # at the trailing slot -- 'Bridge (A.B)' is the control that 

370 # proves the guard load-bearing (without it the nickname reading 

371 # of 'A.B' gains a spurious SUFFIX_OR_NICKNAME report in post_rules), and 

372 # 'Bridge (1.4)' cannot exercise it, a digit chunk never reaching 

373 # the shape verdict at all (period_joined_vocab's alphabetic 

374 # gate). 

375 if "vocab:title" not in tags and "vocab:suffix" not in tags: 

376 derived = period_joined_vocab(token.text, lex) 

377 if derived == "title": 

378 tags.add("vocab:title") 

379 # rules/H5: "a word with interior periods every one of whose 

380 # chunks is a title chains without a final period" -- marked 

381 # as a title listed whole is (decisions/H5, #1131) 

382 if period_joined_title(token.text, lex): 

383 tags.add(JOINED_TITLE_TAG) 

384 elif derived == "suffix": 

385 tags.add("vocab:suffix") 

386 elif (derived == "shape" and token.role is None 

387 and n not in lex._sets.suffix_acronyms_ambiguous): 

388 # This branch and `_vocab.ambiguous_class_candidate` ask 

389 # the SAME question twice, of necessity -- `segment` runs 

390 # before `classify` and has no tags to read yet -- kept 

391 # from drifting by `test_classify. 

392 # test_ambiguous_class_candidate_agrees_with_the_tag` 

393 # rather than by this sentence alone. 

394 # 

395 # `n not in suffix_acronyms_ambiguous` is the third guard, 

396 # and it is about a LISTED member rather than a role: a 

397 # caller may list a dotted entry ('a.b'), which the whole- 

398 # token membership test above matches while 

399 # `suffix_as_written`'s period-free acronym lookup ('ab') 

400 # misses, so the chunk view reached here and called the 

401 # word by-shape -- silencing `_pieces.listed_lean`, which 

402 # declines wherever SHAPE_ACRONYM_TAG rides, and costing 

403 # the caller's own listing its case lean ('Jack A.B.' read 

404 # family where 'Jack MA' reads suffix). One frozenset 

405 # lookup on a branch only a dotted token reaches; the 

406 # shipped ambiguous vocabulary carries no periods, so 

407 # nothing default changes. 

408 tags.add(SHAPE_ACRONYM_TAG) 

409 # rules/S3: "Paired initials are the exception, as C5 defines 

410 # them, in a script that writes capitals" -- the shape 

411 # tag alone, as with the switch off, so the trailing slots 

412 # read them as a name word and report the fork; the comma 

413 # restores the class tag where C5 reads them 

414 # (decisions/S3 (#864)); `is_cased_paired_initials` asks the 

415 # script half ('พ.บ.' is no initial) 

416 if (state.policy.unlisted_dotted_suffixes 

417 and not is_cased_paired_initials(token.text)): 

418 tags.add(AMBIGUOUS_ACRONYM_TAG) 

419 elif (state.policy.unlisted_caps_suffixes is CapsSuffixes.EVERYWHERE 

420 and token.role is None 

421 # what the predicate would decline anyway, asked first in 

422 # C: a listed member ('John Smith, MA'), and a word that 

423 # is not alphabetic capitals ('John Smith, Ph. D.') 

424 and n not in lex._sets.suffix_acronyms_ambiguous 

425 and (token.text.isupper() 

426 and (token.text.isalpha() or "-" in token.text 

427 or "/" in token.text) 

428 or not unicodedata.is_normalized("NFC", token.text)) 

429 and caps_shape_candidate(token.text, lex, state.policy, 

430 one_case, mixed_case=False)): 

431 # #516's all-caps half: an unlisted word written in capitals 

432 # inside a mixed-case name. EVERYWHERE tags it in every 

433 # slot; the default admits it only in the part after a 

434 # comma, which `_comma.decide` reads after this stage and 

435 # tags there when it binds the part (#564, #613), so the 

436 # reading carries the same marks under either setting -- 

437 # case repair keeps 'XYZ' in 'John Smith, XYZ' 

438 # (rules/R4) rather than title-casing a credential the 

439 # default admitted. 

440 # The setting comes FIRST, then C-level checks of what the 

441 # predicate would decline, so the default never calls it 

442 # and EVERYWHERE calls it only for an unlisted all-caps 

443 # word (that is why this half is a call where the dotted branch 

444 # above stays inline: the dotted caller has no such cheap 

445 # first conjunct to hide behind). The predicate's own 

446 # docstring carries the whole-vocabulary roster and what 

447 # each measured entry would have cost unfixed. 

448 tags.add(SHAPE_ACRONYM_TAG) 

449 tags.add(AMBIGUOUS_ACRONYM_TAG) 

450 return frozenset(tags) 

451 

452 

453#: The tags of a word that joins the word after it, which a delimiter 

454#: glued to the word stands between (rules/C10). A particle's are among 

455#: them though it also attaches backward (rules/P6): kept, it chained 

456#: forward across the delimiter ('Berg, de; Smith' read family 'Berg de; 

457#: Smith'), and blocking the forward joins alone would guard every site 

458#: that reads the tag (decisions/C10). 

459_JOINING_TAGS = frozenset({"particle", "conjunction", 

460 "vocab:particle-ambiguous", "vocab:bound-given"}) 

461 

462#: What a word read out of the title gives up (rules/H9): the title tag 

463#: and the two that qualify one, which are read only beside it. 

464_TITLE_TAGS = frozenset({"vocab:title", "vocab:given-title", 

465 "vocab:after-given-title"}) 

466 

467 

468def classify(state: ParseState) -> ParseState: 

469 # One fold per token, shared by the marker pass and the vocabulary 

470 # tags -- the shape suffix_as_written already asks for ("n is 

471 # _normalize(text), passed in so callers normalize once"). 

472 lex = state.lexicon 

473 sets = lex._sets 

474 folded = [_normalize(t.text) for t in state.tokens] 

475 marker_tags = tag_marker_runs(state.tokens, state.comma_offsets, 

476 sets.maiden_markers, folded) 

477 # rules/P3 says a maiden marker, taken as one, and the words it 

478 # takes, are not among the name's own words -- so the span and its 

479 # clause cut are _pieces.own_words', shared with the site that 

480 # needs the same answer two stages earlier (#289/#516). The marker 

481 # map goes with it: this stage has already decided which tokens 

482 # are run HEADS, so the helper reads that decision rather than 

483 # walking the texts again, and classify's answer is the one it was 

484 # before the helper existed. 

485 own, clause_at = own_words(state.tokens, state.comma_offsets, 

486 sets.maiden_markers, marker_tags) 

487 # ONE fact per parse, and it is recorded now (ParseState.one_case): 

488 # segment writes it first where C2's flag on a tail part asks, and 

489 # a fact two stages decide apart is what recording it prevents 

490 # (decisions/S6). 

491 one_case = state.one_case 

492 if one_case is None: 

493 one_case = is_one_case(own) 

494 # The fork itself must not read a clause's words either, so the 

495 # `one_case and ...` argument below repeats `own`'s membership test 

496 # per token, and the fork and its emitter then agree with the case 

497 # class they consult. No extra frame -- it is one more boolean in a 

498 # comprehension that already walks every token. 

499 # rules/T4 asks a word outside the own words about the WHOLE 

500 # name's case (`_tags_for`'s `letter_one_case`). Where every token 

501 # is an own word the two facts are one, so only a name with a 

502 # clause pays the second test's frame. 

503 whole_one_case = one_case and ( 

504 len(own) == len(state.tokens) 

505 or is_one_case([t.text for t in state.tokens])) 

506 # rules/C10: "the word keeps the delimiter in its text and reads as 

507 # it would without it" -- tagged as the word without it ('MD;' as 

508 # 'MD'), so every reading that asks a word's vocabulary asks the 

509 # stem's; only where the delimiter "stands after the first comma", 

510 # a semicolon before it being a word (decisions/C10, D15) 

511 readers = list(state.tokens) 

512 stemmed: set[int] = set() 

513 if state.comma_offsets: 

514 policy_cores = state.policy.extra_suffix_delimiters 

515 cores = (BUILTIN_GLUED_DELIMITERS if not policy_cores 

516 else glued_cores(policy_cores)) 

517 first = state.comma_offsets[0] 

518 for i, t in enumerate(state.tokens): 

519 text = t.text 

520 if t.span.start < first: 

521 continue 

522 for core in cores: 

523 if core in text: 

524 stem = glued_stem(text, cores) 

525 if stem is not None: 

526 readers[i] = copy_with(t, text=stem) 

527 folded[i] = _normalize(stem) 

528 stemmed.add(i) 

529 break 

530 # rules/S1: "the comma is no part of the word it is written against" 

531 # -- a word of a delimited clause keeps a comma written beside it 

532 # (N1), and is tagged as the word without it, so a clause S1 sets apart 

533 # gives each word its vocabulary whichever side of the comma it 

534 # stands ('(Jr, PhD)', '(MBA, PhD)'); a maiden marker's comma 

535 # unmakes the marker (M3), which the marker pass above has already 

536 # read off the word as written (decisions/S1, #792), and so does an 

537 # alias marker's (rules/N4), which keeps its comma here to be read 

538 # as no marker 

539 if state.extracted: 

540 for i, t in enumerate(state.tokens): 

541 if (t.role is not None and i not in marker_tags 

542 and (bare := t.text.strip(COMMA_STRIP)) and bare != t.text): 

543 fold = _normalize(bare) 

544 if fold in sets.alias_markers: 

545 continue 

546 readers[i] = copy_with(t, text=bare) 

547 folded[i] = fold 

548 # a list, not a generator: tuple() over a generator cost a frame 

549 # per token for each resume 

550 tokens = tuple([ 

551 copy_with( 

552 t, tags=_tags_for(readers[i], folded[i], state, marker_tags.get(i), 

553 one_case_own=one_case and i < clause_at 

554 and t.role is None, one_case=one_case, 

555 letter_one_case=whole_one_case or ( 

556 one_case and i < clause_at 

557 and t.role is None))) 

558 for i, t in enumerate(state.tokens)]) 

559 # A word with a delimiter glued to it joins no neighbour across the 

560 # delimiter, so the stem's joining tags stay off it: 'y;' is no 

561 # connective to the word after it (rules/C10: "no join, maiden 

562 # clause or connective reaches across it") 

563 if stemmed: 

564 # a loop, not a generator, which is a frame per token resumed 

565 written = list(tokens) 

566 for i in stemmed: 

567 written[i] = copy_with(written[i], tags=written[i].tags - _JOINING_TAGS) 

568 tokens = tuple(written) 

569 # rules/H9: "the word is a title only inside a title phrase, and 

570 # elsewhere a name word" -- the phrase test (_vocab.title_readings) 

571 # asked per part, of the words carrying no role, and only of a part 

572 # holding one, so that a name with neither pays no frame. A word read out of the title keeps no 

573 # title tag, and every later stage reads it as the name word it is; 

574 # a contested word keeps TITLE_AMBIGUOUS_TAG either way, for the 

575 # report where it opens the name (assign) (decisions/H9 (#752)) 

576 # rules/H10: "a title that is also a given name reads it as the 

577 # title it spells when asking for a partner in its title phrase 

578 # (H9)" -- the run's spelling without stops goes to the phrase test 

579 # wherever it stands, as its undotted twin does. Only where the name 

580 # holds a word that test reads, so a run alone ('U.S. Grant') runs 

581 # no phrase test; whether the run is kept as a title is the title 

582 # runs' question, not this one (decisions/H10) 

583 if not (sets.titles_ambiguous.isdisjoint(folded) 

584 and sets.title_modifiers.isdisjoint(folded)): 

585 for i, t in enumerate(tokens): 

586 if DOTTED_TITLE_TAG in t.tags: 

587 folded[i] = folded[i].replace(".", "") 

588 # asked again, of the folds the stops came off 

589 if not (sets.titles_ambiguous.isdisjoint(folded) 

590 and sets.title_modifiers.isdisjoint(folded)): 

591 written = list(tokens) 

592 for at, seg in enumerate(state.segments): 

593 own_part = [i for i in seg if written[i].role is None] 

594 norms = [folded[i] for i in own_part] 

595 if (sets.titles_ambiguous.isdisjoint(norms) 

596 and sets.title_modifiers.isdisjoint(norms)): 

597 continue 

598 readings = title_readings( 

599 [readers[i].text for i in own_part], norms, lex, 

600 head=at == 0, 

601 titled=["vocab:title" in written[i].tags for i in own_part]) 

602 for i, title in zip(own_part, readings): 

603 tags = written[i].tags 

604 n = folded[i] 

605 if n not in sets.titles_ambiguous and n not in sets.title_modifiers: 

606 continue 

607 if n in sets.titles_ambiguous and n not in sets.titles: 

608 tags = tags | {TITLE_AMBIGUOUS_TAG} 

609 if title: 

610 # in a title phrase: a title (its given-name title 

611 # tag, if any, `_tags_for` wrote already) 

612 tags = tags | {"vocab:title"} 

613 if not title: 

614 tags = tags - _TITLE_TAGS 

615 if tags != written[i].tags: 

616 written[i] = copy_with(written[i], tags=tags) 

617 tokens = tuple(written) 

618 # rules/P12: "the two words are one name unit, past the first name word" 

619 # -- the phrase test over each word and the word after it, asked 

620 # only of a name holding a bound word, in a plain loop, so that no 

621 # other name pays a frame; the tag goes on the bound word, and 

622 # group joins the pair (decisions/P12, #694). A bound word written 

623 # `completes_any` pairs with a plain word, one carrying no tag (no 

624 # vocabulary reading, not initial-shaped) and holding a letter, and 

625 # one written `long_names_only` too, which post_rules splits back in 

626 # a name of fewer than four name words (decisions/P12, #1464) 

627 # 

628 # the marks each pair's first word takes, written in one pass after 

629 # both walks 

630 bound: dict[int, frozenset[str]] = {} 

631 phrases = sets.bound_phrases 

632 open_bound = sets.bound_completes_any 

633 if ((phrases or open_bound) 

634 and not sets.bound_given_names.isdisjoint(folded)): 

635 for i in range(len(folded) - 1): 

636 # rules/C10: "no join, maiden clause or connective reaches 

637 # across it", so a delimiter glued to the bound word ends it 

638 if i in stemmed: 

639 continue 

640 if f"{folded[i]} {folded[i + 1]}" in phrases: 

641 bound[i] = _BOUND_PHRASE_TAGS 

642 # the first word is P5's, which this join never reads 

643 # a contested title H9 read out of a title phrase is a name word 

644 elif (i and folded[i] in open_bound 

645 and tokens[i + 1].tags <= _CONTESTED_TAGS 

646 and _HAS_LETTER.search(tokens[i + 1].text)): 

647 # a word written `long_names_only` too: whether the name 

648 # holds four name words is the parse's to count, so 

649 # post_rules splits the pair where it does not 

650 bound[i] = _BOUND_PHRASE_TAGS 

651 # rules/P12: "for a pair read from its second word, at it too" -- a word of 

652 # Lexicon.bound_seconds joins the plain word before it, and a pair of 

653 # Lexicon.bound_second_phrases joins whole, wherever it stands, the 

654 # first name word included; a name of two name words is split back 

655 # once roles are settled (post_rules), as P5's reserve keeps a bound 

656 # word's pair there (decisions/P12, #1072) 

657 seconds = sets.bound_seconds 

658 if not seconds.isdisjoint(folded): 

659 second_phrases = sets.bound_second_phrases 

660 listed = sets.bound_seconds_listed 

661 for i in range(len(folded) - 1): 

662 before, after = tokens[i], tokens[i + 1] 

663 # a word carrying a role (a delimited clause) is in no 

664 # piece group joins, so its tag would be read by nothing 

665 if (folded[i + 1] not in seconds or i in stemmed 

666 or not after.tags <= _CONTESTED_TAGS 

667 # no pair is written across a comma 

668 or state.comma_offsets 

669 and any(before.span.end <= c < after.span.start 

670 for c in state.comma_offsets)): 

671 continue 

672 if f"{folded[i]} {folded[i + 1]}" not in second_phrases and ( 

673 folded[i + 1] in listed or before.tags 

674 or not _HAS_LETTER.search(before.text)): 

675 continue 

676 # a superset of the phrase mark, so it overwrites one the first 

677 # walk wrote 

678 bound[i] = _BOUND_SECOND_TAGS 

679 if bound: 

680 # a loop, not a generator, which is a frame per token resumed 

681 written = list(tokens) 

682 for i, extra in bound.items(): 

683 written[i] = copy_with(written[i], tags=written[i].tags | extra) 

684 tokens = tuple(written) 

685 # rules/S12: "a credential written split across a space reads as one 

686 # word" -- each adjacent pair of a segment asked once, here, and 

687 # the answer written on its first word for group's merge and the 

688 # comma's reading of its part (`_vocab.split_pair`). The shape and 

689 # the fold's membership are asked first, in C, so an ordinary pair 

690 # of words pays no frame; a token carrying a role is delimited 

691 # content, which no pair reaches (decisions/S12 (#752)). 

692 split: dict[int, str] | None = None 

693 acronyms = sets.suffix_acronyms 

694 words = sets.suffix_words 

695 for seg in state.segments: 

696 for j in range(len(seg) - 1): 

697 a, b = tokens[seg[j]], tokens[seg[j + 1]] 

698 if (SPLIT_CHUNK.fullmatch(a.text) is not None 

699 and SPLIT_CHUNK.fullmatch(b.text) is not None 

700 and a.role is None and b.role is None 

701 # the opening letter, the length a superset of the 

702 # predicate's count of composed letters ('i i' folds 

703 # to the listed 'ii' and opens with one) 

704 and (len(a.text.rstrip(".")) >= 2 

705 or a.text.endswith(".") and b.text.endswith(".") 

706 and (len(b.text) == 2 or not b.text.isascii())) 

707 # the Ph./D. pair, which `split_pair` answers by the 

708 # lexicon's `phd` (#1000); any other only where its words 

709 # are not two suffix words, two credentials already, 

710 # and its fold is listed, composed in C where it is 

711 # not ASCII 

712 and (SPLIT_PAIR_OPENS.fullmatch(a.text) is not None 

713 or not ("vocab:suffix" in a.tags 

714 and "vocab:suffix" in b.tags) 

715 and ((fold := (a.text + b.text).replace(".", "") 

716 .lower()) in acronyms or fold in words 

717 or not fold.isascii() 

718 and ((nfc := unicodedata.normalize( 

719 "NFC", fold)) in acronyms 

720 or nfc in words))) 

721 and (kind := split_pair(a.text, b.text, lex)) is not None 

722 # a member pair a connective borders is no credential: 

723 # the connective joins the words beside it 

724 and (kind == "suffix" or ( 

725 j == 0 

726 or "conjunction" not in tokens[seg[j - 1]].tags) 

727 and (j + 2 >= len(seg) 

728 or "conjunction" not in tokens[seg[j + 2]].tags)) 

729 # the Ph./D. pair outranks a pair overlapping it: 

730 # 'Dr. Ph. D.' is no 'Dr. Ph.' ('drph') and a 'D.' 

731 and not (kind == "split" and j + 2 < len(seg) 

732 and split_pair(b.text, tokens[seg[j + 2]].text, 

733 lex) == "suffix")): 

734 if split is None: 

735 split = {} 

736 split[seg[j]] = (SPLIT_CREDENTIAL_TAG if kind == "suffix" 

737 else SPLIT_MEMBER_TAG) 

738 if split is not None: 

739 # a loop, not a generator, which is a frame per token resumed 

740 written = list(tokens) 

741 for i, tag in split.items(): 

742 written[i] = copy_with(written[i], tags=written[i].tags | {tag}) 

743 tokens = tuple(written) 

744 # rules/H5: "successive single words that wear the abbreviation 

745 # shape and are title vocabulary chain into the title from the end" 

746 # -- which words those are, written once as CHAIN_TITLE_TAG for 

747 # every reader of the chain (decisions/H5 (#1171)). After H9's phrase test, which 

748 # settles "vocab:title"; against the text as written, which the 

749 # readers saw before the tag ('Prof.;' wears no shape, C10's stem 

750 # notwithstanding). The tag tests first, in C, so only a title word 

751 # pays the regex, and only one wearing the shape pays a frame, in 

752 # any position ('Dr.' too: position is the readers' question). 

753 chain: list[WorkToken] | None = None 

754 for i, token in enumerate(tokens): 

755 tags = token.tags 

756 if (JOINED_TITLE_TAG in tags 

757 or ("vocab:title" in tags or TRAILING_TITLE_TAG in tags) 

758 and _TRAILING_TITLE_SHAPE.match(token.text) is not None): 

759 if chain is None: 

760 chain = list(tokens) 

761 chain[i] = copy_with(token, tags=tags | {CHAIN_TITLE_TAG}) 

762 if chain is not None: 

763 tokens = tuple(chain) 

764 ambiguities = list(state.ambiguities) 

765 for i, token in enumerate(tokens): 

766 # #383/#479: narrows the fork's own "initial" tag with the same 

767 # inputs the fork used, rather than re-deciding from scratch. 

768 # Only the casedness test is inherited from the tag -- 

769 # `is_initial(token.text)` also tags a bare capital "initial" 

770 # in the fork's else branch, so the tag alone does not tell 

771 # this apart from that. 

772 # 

773 # Of the two clauses beside it, one is load-bearing and one is 

774 # not. `conjunctions_ambiguous` is IMPLIED by the others for a 

775 # fresh parse -- the contrapositive of what it looks like: 

776 # `is_initial` matches an ASCII capital only, so a bare 

777 # LOWERCASE letter is tagged "initial" only by the fork's 

778 # branch ("jose e maria santos" tags a lowercase e), for a 

779 # conjunctions_ambiguous member, or by the one-case letter 

780 # (#721, #723), which never tags an own word that is a 

781 # single-letter connective (the fork's branch takes those 

782 # first). So for a letter of EITHER case in `conjunctions`, 

783 # "initial" plus len 1 implies membership. It is kept only because `_tags_for` 

784 # starts from `set(token.tags)`, so 

785 # this clause is what keeps the emitter honest if a runner ever 

786 # hands classify tokens it did not build; no such path exists 

787 # today. `conjunctions` is the clause doing real work: it keeps 

788 # an orphan marker (a conjunctions_ambiguous entry no longer in 

789 # conjunctions) inert rather than reported (decisions/P8). 

790 # `i < clause_at and token.role is None` mirrors the fork's own 

791 # "own words" test above, for the same reason (rules/P3): a 

792 # clause's words were never eligible for the fork, so they must 

793 # never be eligible to report either. Emitted at the decision 

794 # site (mechanisms.md#AMBIGUITY-AT-THE-DECISION-SITE), per 

795 # token -- 'e and e e' emits twice; assemble withdraws the 

796 # report on a letter no name word follows (rules/P8, #721). 

797 if (one_case and "initial" in token.tags 

798 and folded[i] in sets.conjunctions_ambiguous 

799 and folded[i] in sets.conjunctions 

800 and i < clause_at and token.role is None 

801 and (len(token.text) == 1 

802 or not token.text.isascii() 

803 and composed_len(token.text) == 1)): 

804 ambiguities.append(PendingAmbiguity( 

805 AmbiguityKind.CONJUNCTION_OR_INITIAL, 

806 f"{token.text!r} is both a connective and an initial; " 

807 f"the name is written in one case, so nothing marks " 

808 f"which, and it is read as an initial", 

809 (i,), 

810 # the field of the join it would make is assign's to 

811 # name, once the name has positions 

812 alternative=PendingReading(ReadingKind.CONJUNCTION, 

813 ReadingSource.VOCABULARY, 

814 Deferred.JOINED))) 

815 # The write rides the replace this stage already makes, so 

816 # recording the fact costs no frame of its own. 

817 return copy_with(state, tokens=tokens, 

818 ambiguities=tuple(ambiguities), 

819 one_case=one_case)