diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 2793c2f16..9c880ef92 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -87,14 +87,20 @@ # rules/T1: "at the edge the word is looked up without it" # The zero-width non-joiner and joiner shape the letters on either side # of them, so at a word's edge they shape nothing and are dropped when -# the word is looked up (#1335: `مهندس` typed with a ZWNJ after it is -# the title `مهندس`), with the edge full stops. Inside a word they stay +# the word is looked up, with the edge full stops (decisions/T1, +# #1335). Inside a word they stay # (`آیت‌الله` is listed with its ZWNJ). Token text is never rewritten, # which keeps the ZWJ Malayalam writes at a word's end. _EDGE_JOINERS = "\u200c\u200d" _NON_ASCII_EDGES = FULL_STOPS + _EDGE_JOINERS +def _a(kind: str) -> str: + """The article a message writes before a reading's kind: ``an`` + before a vowel and before ``honorific``, whose h is silent.""" + return "an" if kind[:1] in "aeiou" or kind == "honorific" else "a" + + def _normalize(word: str) -> str: """Lowercase, NFC-compose, strip whitespace and EDGE full stops (FULL_STOPS, not the ASCII period alone -- #322), and in a non-ASCII @@ -1027,7 +1033,7 @@ def _prop_value(kind: str, prop: str, value: object) -> object: side = ("before" if _index_module().CATEGORY.get(kind) == "title" else "after") if value != side: - raise ValueError(f"attached on a {kind!r} reading must be " + raise ValueError(f"attached on {_a(kind)} {kind!r} reading must be " f"{side!r} (a {'title peeled off the start' if side == 'before' else 'tail peeled off the end'} " f"of a name token) or None, got {value!r}") return value @@ -1057,9 +1063,13 @@ def _prop_value(kind: str, prop: str, value: object) -> object: # an empty list would leave `completes` unwritten, which # joins behind ANY plain word, the widest reading; the build # refuses it too (#1072) + cleared = ("joins it behind any plain word" + if prop == "completes" + else "leaves no listed word completing it") raise ValueError(f"{prop} must list at least one word, got " - f"{value!r}; write {prop}=None to clear a " - f"list the word's reading has") + f"{value!r}; list the words it pairs with, or " + f"write {prop}=None to clear the list, which " + f"{cleared}") if prop in ("completed_by", "completes") and any(" " in w for w in folded): # rules/P12 joins two words: a bound word to the one word # after it (completed_by), a bound_second word to the one @@ -1196,7 +1206,7 @@ def _edit_props(kind: str, props: Mapping[str, object]) -> _Props: "write add(word, kind='given', after_particle=True)") if prop not in allowed: raise ValueError( - f"a {kind} reading takes " + f"{_a(kind)} {kind} reading takes " + (", ".join(sorted(allowed)) or "no properties") + f"; got {prop!r}") out[prop] = _prop_value(kind, prop, value) @@ -1241,7 +1251,7 @@ def _make_edit(op: object, words: object, kind: object, if " " in w and not (k == "birth_marker" or ( category == "title" and ("addresses", "given") in p)): raise ValueError( - f"{w!r} is a phrase, which can never match as a {k}: only " + f"{w!r} is a phrase, which can never match as {_a(k)} {k}: only " f"a birth_marker and a title with addresses='given' are " f"matched as a whole run; add its words one by one") # the build refuses attached on a title phrase: the glued-title @@ -1782,7 +1792,7 @@ def _check_base(base: object) -> object: if name not in ri.indexed(kind): raise ValueError( f"a Lexicon snapshot gives {word!r}'s {kind} reading " - f"the property {name!r}, which a {kind} reading " + f"the property {name!r}, which {_a(kind)} {kind} reading " f"does not take in this release") try: hash(value) @@ -1985,7 +1995,7 @@ class LexiconReading: kind: str #: The kind's category (``"title"``, ``"suffix"``, ``"particle"``, #: ``"conjunction"``, ``"bound_given"``, ``"bound_second"``, - #: ``"relation"``, ``"name"``). + #: ``"relation"``, ``"name"``, ``"familiar"``, ``"spelling"``). category: str #: The behavioral properties as sorted ``(name, value)`` pairs, #: spelled as the files spell them (``("addresses", "given")``), a @@ -2006,7 +2016,7 @@ def __post_init__(self) -> None: f"kinds are {', '.join(ri.CATEGORY)}") if self.category != ri.CATEGORY[self.kind]: raise ValueError( - f"a {self.kind} reading's category is " + f"{_a(self.kind)} {self.kind} reading's category is " f"{ri.CATEGORY[self.kind]!r}, got {self.category!r}") for name in ("properties", "languages"): if not isinstance(getattr(self, name), tuple): diff --git a/nameparser/_parser.py b/nameparser/_parser.py index 1c3ca5f19..8e54a807e 100644 --- a/nameparser/_parser.py +++ b/nameparser/_parser.py @@ -314,8 +314,9 @@ def suggest(self, names: Iterable[str]) -> Suggestion: the base: a :class:`~nameparser.Suggestion` whose ``parser`` reads the group. ``names`` is any iterable of str the caller declares to be one group (one source, one convention), read - once. Each name casts votes on its name order and its - patronymic shape, read with this parser's lexicon past the + once. Each name casts votes on its name order, its patronymic + shape and, where the switch is weighed (below), + ``two_family_names``, read with this parser's lexicon past the titles it lists at the head and the post-nominals at the end; a name of fewer than two words once those are read past casts none, and so does a name with a comma, unless only @@ -409,48 +410,29 @@ def suggest(self, names: Iterable[str]) -> Suggestion: an empty group, or one with no votes, suggests no change. A bare str, bytes, a mapping or a non-str item raises TypeError. - Measured 2026-11-10, re-taken 2026-11-11, 2026-11-12, - 2026-11-14, 2026-11-15, 2026-11-16 and 2026-11-19, with - tools/differential/suggest_measure.py on groups drawn from real - names written in a known order, 300 groups a size - (decisions/group-suggestion's 2026-11-19 #1364 and #1447 - entries hold the sizes): a group written in this parser's own order kept it - in at least 97% of groups at every size from 2 to 2,000 names, - under either base order, save three lists. ORCID holders who - typed their given name in capitals (``ANNA Smith``), which the - capitals signal reads as a family name, kept their given-first - order in 52% of groups of two and 4% of five (why, in that - file's 2026-11-12 CAPITALS entry). A list of - nothing but bylines written two or three joined initials first - (``AM Hoy``) kept it in at least 97% of groups at every size - measured, to 500 names (it holds 644), but 50 and 100 names, - where it kept it in 94.7% and 93.3%, the name tables voting on - a few of its names. And a list of nothing but given names that - ORCID's holders type as surnames (``Cooper``, ``Burke``) fell - below 95% at every size and was read wrong in every group from - 5 names, the surname table voting on each of them (that file's - 2026-11-19 #1364 entry). - Moving the base takes more names, and - how many depends on what the names carry: groups of Chinese, - Taiwanese, Korean, Czech, Polish or Italian names (the romanized - surnames and the common given names) and of Russian ones (where - their patronymics stand) were read right in 95% of groups from 5 - names; German, Dutch, Spanish, British, French, - Romanian, Vietnamese and Japanese from 10; US, Turkish, - Nigerian and Brazilian from 20; Indian from 50; and PSC's - Bangladeshi filers from 200 (PatentsView's Philippine inventors - from 20, through the Russian names among them). A group whose votes fall short of - the thresholds keeps the base rather than guess, so a smaller - group moves it in fewer of the draws. ``capitals_as_family``, measured 2026-11-12 - (decisions/group-suggestion's CAPITALS entry): ORCID holders who - typed their family name in capitals were suggested it in at least - 95% of groups from 4 names, and from 10 where many of the - surnames are two or three letters (holders in China, Korea, - Vietnam and Taiwan). Of the lists measured that do not write their - family names so, only ORCID holders who typed their given name in - capitals (``ANNA Smith``) were suggested it, which nothing in a - name tells apart; no other list was, ORCID's bylines (``AM Hoy``) - included. A name wholly in one case carries no evidence. + Measured on groups drawn from real names written in a known + order (:ref:`suggest-limits`; the dated tables are in the + source repository's docs/design/decisions/group-suggestion.md), + these figures give a general idea and will differ for every + dataset. A group written in this parser's own order kept it in + at least 95% of groups from 2 to 2,000 names, and in 97% for + nearly every kind, save three kinds of list: given names in + capitals (``ANNA Smith``), whose capitals read as a family name; + nothing but two or three joined initials (``AM Hoy``), which + kept it in just under 95% of groups of 50 and 93% of 100; and + nothing but given names that are common surnames elsewhere + (``Cooper``, ``Burke``), read the wrong way round. A group + written the other way round takes more names to move the base: + from 5 for Chinese, Taiwanese, Korean, Czech, Polish, Italian + and Russian names to 50 for Indian ones and 200 for Bangladeshi + ones. A group whose votes fall short of the thresholds keeps the + base rather than guess. ``capitals_as_family`` was suggested in + at least 95% of groups from 4 names for holders who typed their + family name in capitals, and from 10 where many of the surnames + are two or three letters (China, Korea, Vietnam and Taiwan); of + the lists that do not write their family names so, only the one + writing its given names in capitals was suggested it. A name + wholly in one case carries no evidence. """ from nameparser._suggest import suggest return suggest(self, names) diff --git a/nameparser/_pipeline/_assign.py b/nameparser/_pipeline/_assign.py index 4bdde3860..8cd3aef1c 100644 --- a/nameparser/_pipeline/_assign.py +++ b/nameparser/_pipeline/_assign.py @@ -2060,23 +2060,19 @@ def as_a_middle(m: int, token: WorkToken) -> PendingReading: # rules/H6: "A run of title words opening the part before a # family comma is the title" -- by vocabulary only, never H2's # shape, leaving one piece for the family, and stopping at a - # word that is a particle too ('St Pierre', 'Freiherr von - # Berg'), or where everything behind it is post-nominal, which - # leaves no family word to address -- H3's concern, by a - # stricter test than H3's one-word give-back, so this is not - # `leading_titles` ('VC PhD Jr., John' keeps family 'VC', where - # 'VC PhD Jr. John' reads title 'VC'). A dual is a title wherever - # a name word follows it ('Rev. Sr. Smith, Mary'). - # `is_title_piece` is H5's vocabulary read, so the two slots that - # refuse the shape agree on what a title word is, save H5's - # written-short clause, which this slot does not read - # (decisions/H9, #999: 'Maj. Smith, John' keeps family 'Maj. Smith'). + # word that is a particle too, or where everything behind it is + # post-nominal, which leaves no family word to address -- H3's + # concern, by a stricter test than H3's one-word give-back, so + # this is not `leading_titles`. A dual is a title wherever a name + # word follows it. `is_title_piece` is H5's vocabulary read, so + # the two slots that refuse the shape agree on what a title word + # is, save H5's written-short clause, which this slot does not + # read (decisions/H6, decisions/H9 (#999)). # # rules/H10: "where a title the run keeps stands behind it" -- - # a dotted run ('U.S. Senator Smith, John') counts as a title - # word here as in the leading run, and one the run ends on is - # given back ('U.S. Grant Smith, John' keeps family 'U.S. Grant - # Smith'), so the roles are set once the run is known. + # a dotted run counts as a title word here as in the leading + # run, and one the run ends on is given back, so the roles are + # set once the run is known (decisions/H10 (#490)). lead = 0 floor = len(fam_pieces) # the length test and the tag test first, both C-level: a part diff --git a/nameparser/_pipeline/_classify.py b/nameparser/_pipeline/_classify.py index b9e761775..9e0811ea1 100644 --- a/nameparser/_pipeline/_classify.py +++ b/nameparser/_pipeline/_classify.py @@ -624,6 +624,7 @@ def classify(state: ParseState) -> ParseState: # vocabulary reading, not initial-shaped) and holding a letter, and # one written `long_names_only` too, which post_rules splits back in # a name of fewer than four name words (decisions/P12, #1464) + # # the marks each pair's first word takes, written in one pass after # both walks bound: dict[int, frozenset[str]] = {} diff --git a/nameparser/_pipeline/_group.py b/nameparser/_pipeline/_group.py index ed4ef8ebe..e864ebb8f 100644 --- a/nameparser/_pipeline/_group.py +++ b/nameparser/_pipeline/_group.py @@ -2001,7 +2001,7 @@ def group(state: ParseState) -> ParseState: # and the same reason, as _extract._overlaps and _tokenize's origin # resolution. test_benchmark's maiden_pairs shape is the guard. # rules/N4: "the marker dropped as M3 drops it" -- a nickname - # clause opening with an alias marker, by the same walk (#1164). + # clause opening with an alias marker, by the same walk (decisions/N4 (#1164)). # A plain loop over a map of a C getter, no frame: a name with no # clause pays nothing, and one with a clause no frame for the starts starts = list(map(_SPAN_START, tokens)) if state.extracted else [] diff --git a/nameparser/_pipeline/_post_rules.py b/nameparser/_pipeline/_post_rules.py index 09216d915..c763b32ae 100644 --- a/nameparser/_pipeline/_post_rules.py +++ b/nameparser/_pipeline/_post_rules.py @@ -806,12 +806,11 @@ def _take_second_family_name(state: ParseState, tokens: list[WorkToken], if not any(ch.isalpha() for i in take for ch in tokens[i].text): return # rules/O6: "a listed given name stays where it is" -- the caller's - # Lexicon.given_names (empty by default; the es, es_ar, pt_br and - # pt_pt packs carry a list, with the switch on) names a word only a given name is, under - # either order. Only a unit of one token is asked: a word - # behind a particle ("de Miguel") is a unit of two, a surname taken - # as before. History: decisions/O6 (#959). - # A hyphenated word writing given names stays too (#959). + # Lexicon.given_names (empty by default; a pack turning O6 on may + # carry one) names a word only a given name is, under either order, + # and a hyphenated word writing given names stays too. Only a unit + # of one token is asked: a word behind a particle ("de Miguel") is a + # unit of two, a surname taken as before (decisions/O6 (#959)). if len(take) == 1 and ( is_listed_given_name(tokens[take[0]].text, state.lexicon) or _hyphenated_given(tokens[take[0]].text, state.lexicon)): diff --git a/nameparser/_policy.py b/nameparser/_policy.py index f82a88cb5..ad4f9b818 100644 --- a/nameparser/_policy.py +++ b/nameparser/_policy.py @@ -989,9 +989,10 @@ class Policy: #: ``Carlos Pérez``), which is most English and Argentine names of #: three words or more and many Portuguese and Brazilian ones as #: filed: switched on for a mixed population it costs more names - #: than it mends, so it is off by default and reports nothing. Runs - #: before middle_as_family, which then folds whatever middles are - #: left. + #: than it mends, so it is off by default and reports nothing; + #: Parser.suggest may suggest it for a group written given name + #: first (Signal.FIRST_SURNAME). Runs before middle_as_family, which + #: then folds whatever middles are left. two_family_names: bool = False #: Reads the given name as two name units, for data where a person #: carries a compound given name and no middle name (rules/O7): diff --git a/nameparser/_suggest.py b/nameparser/_suggest.py index 66080e409..06a092646 100644 --- a/nameparser/_suggest.py +++ b/nameparser/_suggest.py @@ -135,36 +135,36 @@ class Signal(StrEnum): patronymic rule or ``two_family_names``.""" #: A family name written in capitals at one end of a name in mixed - #: case (``Mary SMITH``). + #: case (``Mary SMITH``); votes on the order. CAPITALS = "capitals" - #: A trailing initial (``Smith J.``), counted only where enough of - #: the group's names end in initials. + #: Initials ending the name (``Smith J.``), counted only where enough + #: of the group's names end in them, as a bibliography's do; votes on + #: the order. TRAILING_INITIAL = "trailing-initial" - #: A lowercase particle first or before the last word. + #: A lowercase particle first or before the last word; votes on the + #: order. PARTICLE = "particle" #: A common surname as the first or last word: a romanized Chinese, - #: Korean or Vietnamese one, or one ORCID's holders rarely type as a - #: given name (``García``, #1364). + #: Korean or Vietnamese one, or one researchers rarely write as a + #: given name (``García``, ``Quispe``); votes on the order. SURNAME = "surname" #: A common given name that is rarely a surname (``Emily``, not - #: ``Taylor``) as the first or last word. + #: ``Taylor``) as the first or last word; votes on the order. GIVEN_NAME = "given-name" - #: A patronymic one rule reads (Russian ``Petrovich``, Azerbaijani - #: ``Huseyn oglu``), the evidence on ``patronymic_rules``. + #: A patronymic a rule reads (Russian ``Petrovich``, Azerbaijani + #: ``Huseyn oglu``); votes on ``patronymic_rules``. PATRONYMIC = "patronymic" - #: Where an East Slavic patronymic of three name words stands, read - #: where rules/O1 reads it, the evidence on ``name_order``: in the - #: middle (``Ivan Petrovich Sidorov``) the family is written last, - #: the middle word winning where the last ends as a patronymic too; - #: last (``Sidorov Ivan Petrovich``) it is written first. Cast only - #: beside an East Slavic ``PATRONYMIC`` vote. + #: Where a Russian-style patronymic stands in a name of three words: + #: last (``Sidorov Ivan Petrovich``), the family name is written + #: first; in the middle (``Ivan Petrovich Sidorov``), last. Cast only + #: beside a Russian-style ``PATRONYMIC`` vote; votes on the order. PATRONYMIC_POSITION = "patronymic-position" - #: The word ``two_family_names`` would take into a name's family - #: (rules/O6), voting the switch's value: True where it is a common - #: surname of the ORCID table (``COMMON_SURNAMES``, #1364), ``García`` - #: in ``Gabriel García Márquez``, a first surname standing where a - #: second given name would; False where it is a father's name the - #: switch would read as a first surname (``Ivan Petrovich + #: The word ``two_family_names`` would take into a name's family, + #: voting the switch's value: True where it is a surname researchers + #: rarely write as a given name, the second of the tables ``SURNAME`` + #: names (``García`` in ``Gabriel García Márquez``, a first surname where + #: a second given name would stand), False where it is a father's + #: name the switch would read as a first surname (``Ivan Petrovich #: Sidorov``). A listed given name there casts no vote. FIRST_SURNAME = "first-surname" @@ -608,6 +608,15 @@ def _order_ends(pairs: Iterable[tuple[Signal, Vote]] if _SETTING_OF[signal] == _NAME_ORDER) +def _offered(owner: str, signal: Signal, vote_code: str) -> str: + """The code a refused vote's message offers, in its owner's shape: a + NameEvidence vote is a mapping entry, a SettingEvidence row a + triple.""" + return (f"{{Signal.{signal.name}: {vote_code}}}" + if owner == "NameEvidence" + else f"(Signal.{signal.name}, {vote_code}, 2)") + + def _checked_vote(signal: object, vote: object, owner: str = "NameEvidence") -> tuple[Signal, Vote]: """One (signal, vote) pair, validated: an order signal votes @@ -620,14 +629,14 @@ def _checked_vote(signal: object, vote: object, if not isinstance(vote, bool): raise TypeError( f"{owner} vote for {signal.value!r} must be True or False, " - f"got {vote!r}; pass e.g. {{Signal.{signal.name}: True}}") + f"got {vote!r}; pass e.g. {_offered(owner, signal, 'True')}") return signal, vote if setting == _PATRONYMIC_RULES: if not isinstance(vote, PatronymicRule): raise TypeError( f"{owner} vote for {signal.value!r} must be a " f"PatronymicRule, got {vote!r}; pass e.g. " - f"{{Signal.PATRONYMIC: PatronymicRule.EAST_SLAVIC}}") + f"{_offered(owner, signal, 'PatronymicRule.EAST_SLAVIC')}") return signal, vote if not isinstance(vote, (tuple, list)): raise TypeError( @@ -656,6 +665,15 @@ def _iterable(value: object, owner: str, form: str, example: str return tuple(value) +#: A ``by_signal`` row each setting takes, which a refused row's message +#: offers: one whose signal votes on that setting +_ROW_EXAMPLE: Mapping[str, str] = MappingProxyType({ + _NAME_ORDER: "(Signal.SURNAME, FAMILY_FIRST, 2)", + _PATRONYMIC_RULES: "(Signal.PATRONYMIC, PatronymicRule.EAST_SLAVIC, 2)", + _TWO_FAMILY_NAMES: "(Signal.FIRST_SURNAME, True, 2)", +}) + + def _checked_row(row: object, setting: str) -> tuple[Signal, Vote, int]: """One ``by_signal`` row, validated: ``(signal, vote, count)``, its signal one that votes on ``setting``.""" @@ -663,8 +681,9 @@ def _checked_row(row: object, setting: str) -> tuple[Signal, Vote, int]: or len(row) != 3: raise TypeError( f"SettingEvidence by_signal rows must be (signal, vote, count) " - f"triples, got {reprlib.repr(row)}; pass e.g. " - f"(Signal.SURNAME, FAMILY_FIRST, 2)") + f"triples, got {reprlib.repr(row)}; " + + (f"pass e.g. {_ROW_EXAMPLE[setting]}" if setting in _ROW_EXAMPLE + else f"no signal votes on {setting}, so pass by_signal=()")) signal, vote, count = row pair = _checked_vote(signal, vote, "SettingEvidence by_signal") if _SETTING_OF[pair[0]] != setting: @@ -713,7 +732,12 @@ class NameEvidence: Order votes are one per NAME: the end the name's order signals agree on. A name whose order signals point at both ends is contested, casts no order vote and never disagrees on order. - ``votes`` keeps every signal's vote all the same, save a + ``votes`` holds the votes keyed by signal: an order vote is the + order it votes for (``GIVEN_FIRST`` or ``FAMILY_FIRST``), a + patronymic vote the ``PatronymicRule``, and a first-surname vote + ``True`` or ``False``, cast only where ``two_family_names`` is + weighed (not where the base has it on or an East Slavic rule is + decided). It keeps every signal's vote all the same, save a trailing-initial vote the group did not cast: too few of its names ending in initials (``Parser.suggest``), or its runs of letters decided ``initials_as_family``, whose letters are its family. @@ -856,7 +880,8 @@ def __post_init__(self) -> None: f"pass '' for no note") rows = _iterable(self.by_signal, "SettingEvidence by_signal", "an iterable of (signal, vote, count) rows", - "((Signal.SURNAME, FAMILY_FIRST, 2),) or ()") + (f"({_ROW_EXAMPLE[self.setting]},) or ()" + if self.setting in _ROW_EXAMPLE else "()")) object.__setattr__( self, "by_signal", tuple(_checked_row(row, self.setting) for row in rows)) diff --git a/nameparser/_types.py b/nameparser/_types.py index 91657aaaf..be871dffe 100644 --- a/nameparser/_types.py +++ b/nameparser/_types.py @@ -47,7 +47,8 @@ class Role(StrEnum): FAMILY = "family" #: Post-nominal pieces ("III", "Jr.", "PhD"). SUFFIX = "suffix" - #: Delimited nickname content ("Jonathan 'Jack' Kennedy" -> "Jack"). + #: Delimited nickname content ("Jonathan 'Jack' Kennedy" -> "Jack"), + #: or the words after an alias marker ("Ali @ Abu bin Ahmad" -> "Abu"). NICKNAME = "nickname" #: A birth surname, from a marker word ("Jane Smith née Jones" -> #: "Jones") or a delimiter pair routed via Policy.maiden_delimiters. @@ -968,7 +969,9 @@ class ReadingSource(StrEnum): #: another category: "Ma" as a surname, "Dean" as a given name. DECLARED = "declared" #: The word's shape, not a list: a roman numeral, letters run - #: together with periods ("X.Y.Z."), a word in capitals. + #: together with periods ("X.Y.Z."), a word in capitals, or after a + #: comma, in a name written in mixed case, a word that opens with two + #: capitals or ends in one ("MRes"). SHAPE = "shape" #: Nothing lists or shapes the word into this reading; it is the #: reading any word has where it stands, an ordinary name word. A @@ -1488,9 +1491,12 @@ def suffix(self) -> str: def nickname(self) -> str: """The words written inside nickname delimiters (quotes, parentheses; :attr:`Policy.nickname_delimiters - `), space-joined in - written order, the delimiters dropped; ``''`` for a name with - none.""" + `), the delimiters + dropped, and the words after a listed alias marker (by default + ``@`` or ``urf`` written as a word of its own: ``Ali @ Abu bin + Ahmad`` gives ``Abu``), the marker dropped, space-joined in + written order; + ``''`` for a name with none.""" return self._text_for(Role.NICKNAME) @property @@ -1637,9 +1643,11 @@ def _first_unit(self) -> bool: @property def surname1(self) -> str: """The family's first name unit where the parse read the family - as two (``García`` in ``Gabriel García Márquez`` under - ``two_family_names``, ``de la Vega`` in ``Juan de la Vega del - Valle`` under it too), :attr:`surname2` being the other; + as two (``García`` in ``Gabriel García Márquez`` and in ``García + Márquez, Gabriel`` under ``two_family_names``, ``de la Vega`` in + ``Juan de la Vega del Valle`` under it too, ``王`` + in ``王李小明`` under ``locales.ZH``), :attr:`surname2` being the + other; elsewhere the whole :attr:`family`. A middle name ``middle_as_family`` folds into the family is in neither (``María García`` in ``Ana María García López`` under @@ -1870,6 +1878,8 @@ def capitalized(self, lexicon: Lexicon | None = None, *, outside the suffix are written in more than one case, and in a name it does repair keeps a suffix written in more than one case as written ('EdD'), repairing only one written in a - single case (rules/R5). Idempotent.""" + single case (rules/R5); force=True repairs that suffix too, save + an unlisted credential read by its mixed case after a comma + ('MRes'), which it keeps as written. Idempotent.""" import nameparser._render as _render return _render.capitalized(self, lexicon, force=force) diff --git a/nameparser/locales/vi.py b/nameparser/locales/vi.py index f0dd7ab3a..ebb990025 100644 --- a/nameparser/locales/vi.py +++ b/nameparser/locales/vi.py @@ -14,7 +14,8 @@ the English credential would take it (decisions/vocabulary-model, the 2026-11-05 #1108 entry). -The fragment is the one pack content that removes: a choice prefers +The fragment removes readings rather than adding them, as only +locales.CS's does besides (``Ing``'s given reading): a choice prefers only by a vocabulary reading, and a name reading never settles a clash (decision 15 of decisions/vocabulary-model), so no reading vi.toml could write makes ``van`` a name word under a plain choice. The order diff --git a/tests/v2/cases.py b/tests/v2/cases.py index 59dccdaed..df3e5024d 100644 --- a/tests/v2/cases.py +++ b/tests/v2/cases.py @@ -1594,7 +1594,7 @@ def _check_cjk_shape_purity(self) -> None: notes="an accepted cost: the gated class written without its " "last stop is no dotted acronym, and the one-word part " "after a family comma is the given name, as 'Jane Doe, " - "M.A' reads on master (decisions/vocabulary-collisions, " + "M.A' reads (decisions/vocabulary-collisions, " "2026-11-21 #1483); 1.4.0 through 3.1.0 read suffix 'R.A'"), Case("ra_alone_after_a_family_comma_in_capitals_is_the_credential", "Doe, RA", @@ -1654,7 +1654,7 @@ def _check_cjk_shape_purity(self) -> None: ambiguities=("suffix-or-name",), notes="an accepted cost: a title that is also a given name is a " "title only inside a phrase (rules/H9), as 'Smith, Dean " - "John' reads on master; 1.4.0 through 3.1.0 read title " + "John' reads; 1.4.0 through 3.1.0 read title " "'RA', given 'John'"), Case("ra_without_its_last_stop_ending_a_name_is_the_family", "Jane Doe R.A", @@ -1663,7 +1663,7 @@ def _check_cjk_shape_purity(self) -> None: ambiguities=("suffix-or-name",), notes="an accepted cost, the no-comma twin of 'Jane Doe, R.A': " "no dotted acronym (rules/S3), so the gate reads the name " - "word, as 'John Smith M.A' reads on master; 1.4.0 through " + "word, as 'John Smith M.A' reads; 1.4.0 through " "3.1.0 read suffix 'R.A'"), Case("ra_in_capitals_before_a_generation_comma_leaves_a_lone_given", "Kim RA, Jr.", @@ -1720,7 +1720,7 @@ def _check_cjk_shape_purity(self) -> None: classification="feat(#1483)", notes="an accepted cost, cost 1's worst shape: 'Dr.' behind a " "given name is no leading title, as 'Dean Dr. Hans Müller' " - "reads on master; 1.4.0 through 3.1.0 read title 'RA Dr.'"), + "reads; 1.4.0 through 3.1.0 read title 'RA Dr.'"), Case("ra_opening_a_family_first_given_last_name_is_the_family", "Ra Mi Kim", {"given": "Kim", "middle": "Mi", "family": "Ra"}, @@ -7783,7 +7783,7 @@ def _check_cjk_shape_purity(self) -> None: "Іван Петренко д-р", {"given": "Іван", "family": "Петренко", "suffix": "д-р"}, classification="fix(#1128)", - notes="master read middle 'Петренко', family 'д-р'"), + notes="1.4.0 through 3.1.0 read middle 'Петренко', family 'д-р'"), Case("a_cyrillic_doctorate_after_a_comma_is_a_credential", "Іван Петренко, д-р", {"given": "Іван", "family": "Петренко", "suffix": "д-р"}, @@ -7836,7 +7836,7 @@ def _check_cjk_shape_purity(self) -> None: {"given": "Иван", "middle": "Петрович", "family": "Сидоров", "suffix": "д-р"}, classification="fix(#1128)", locale="ru", - notes="master read given 'Сидоров', family 'д-р'"), + notes="2.0.0 through 3.1.0 read given 'Сидоров', middle 'Иван Петрович', family 'д-р'"), Case("a_professor_before_a_trailing_doctorate_stays_the_title", "Іван Петренко, проф. д-р", {"title": "проф.", "given": "Іван", "family": "Петренко", "suffix": "д-р"}, @@ -7853,8 +7853,9 @@ def _check_cjk_shape_purity(self) -> None: classification="fix(#1128)", ambiguities=("suffix-or-name",), notes="accepted (decisions/H5, 2026-11-21 #1128): the shape of the " - "one ORCID record holding д-р; master read family 'доц. " - "д-р Мария Петрова', and a Bulgarian choice reads it whole"), + "one ORCID record holding д-р; 1.4.0 through 3.1.0 read " + "family 'доц. д-р Мария Петрова', and a Bulgarian choice " + "reads it whole"), Case("cyrillic_initials_spelling_the_degree_behind_one_word", "Петрова, Д.М.", {"given": "Д.", "middle": "М.", "family": "Петрова"}, @@ -13404,7 +13405,7 @@ def _check_cjk_shape_purity(self) -> None: "credential run now, one entry 'PhD | FACS'. The parting " "half it pinned is held by test_post_rules' " "test_a_surviving_name_word_parts_two_entries on a name " - "word that survives ('Smith, Jane abd Jones PhD'). As " + "word that survives ('Smith, Jane abd de Jones PhD'). As " "pinned under #436/#437: " "the other half, and the one a dropped-core test alone " "would miss. After a FAMILY comma segment 1 is not a " @@ -14180,8 +14181,10 @@ def _check_cjk_shape_purity(self) -> None: "(decisions/P12)"), Case("bound_given_latin_past_the_start_stays_apart", "Tariq Abdul Aziz", {"given": "Tariq", "middle": "Abdul", "family": "Aziz"}, - notes="#694's Latin half: abdul lists no completed_by, the pair " - "being a middle name as often as a family (decisions/P12)"), + notes="#694's Latin half: abdul lists no completed_by, and its " + "completes_any reading is long_names_only (#1464), so in a " + "name of three words the pair stays apart, a middle name " + "as often as a family (decisions/P12)"), Case("mr_and_mrs", "Mr. and Mrs. John Smith", {"title": "Mr. and Mrs.", "given": "John", "family": "Smith"}), Case("roman_suffix", "John Smith V", @@ -17361,8 +17364,8 @@ def _check_cjk_shape_purity(self) -> None: "whatever stands behind it (rules/C13) -- title 'Dr.', " "suffix 'PSM I' -- so the reset no longer decides it. A " "dual opens nothing, and the reset is what is left " - "deciding this spelling. 1.4.0 read the " - "old spelling suffix 'Dr., I'"), + "deciding this spelling. 1.4.0 read 'Smith, PSM Dr. I' " + "given 'PSM', suffix 'Dr., I'"), Case("family_comma_run_numeral_after_a_split_credential", "Smith, Ph. D. I", {"family": "Smith", "suffix": "Ph. D. I"}, @@ -17956,8 +17959,9 @@ def _check_cjk_shape_purity(self) -> None: classification="fix(#1394)", ambiguities=("suffix-or-name",), notes="Accepted (rules/S8): a title behind it is a name word, as " - "behind a Title-case acronym ('John Smith Md Dr'); 3175314d " - "read title 'PROF', suffix 'MD'"), + "behind a Title-case acronym ('John Smith Md Dr'); 2.4.0 " + "through 3.1.0 read title 'PROF', suffix 'MD', 1.4.0 " + "through 2.3.0 these fields"), Case("md_in_capitals_before_a_dotted_title_keeps_the_title", "JOHN SMITH MD PROF.", {"given": "JOHN", "family": "SMITH", "title": "PROF.", @@ -17979,8 +17983,8 @@ def _check_cjk_shape_purity(self) -> None: classification="fix(#1394)", ambiguities=("suffix-or-name", "suffix-or-name"), notes="S8 (#1394's review): the same predicate for the Title-case " - "acronym; 3175314d read middle 'Smith', family 'Md', " - "suffix 'VI Jones'"), + "acronym; 3.0.0 through 3.1.0 read middle 'Smith', family " + "'Md', suffix 'VI Jones', 2.4.0 through 2.8.2 as here"), Case("md_in_capitals_before_a_nickname_and_a_shape_numeral", "JOHN SMITH MD (B) VI JONES", {"given": "JOHN", "family": "SMITH", "nickname": "B", @@ -17997,7 +18001,7 @@ def _check_cjk_shape_purity(self) -> None: ambiguities=("suffix-or-name", "suffix-or-name"), notes="S8 (#1394's review): a numeral S10 reads as the " "generation is no name word behind a settled member " - "either; 3175314d read family 'MA', suffix 'VI Jones'"), + "either; 2.7.0 through 3.1.0 read family 'MA', suffix 'VI Jones'"), Case("md_in_capitals_behind_a_particle_chain_still_reports", "JOHN VAN MD MA DE", {"given": "JOHN", "middle": "VAN MD MA", "family": "DE"}, @@ -18005,7 +18009,7 @@ def _check_cjk_shape_purity(self) -> None: ambiguities=("suffix-or-name", "suffix-or-name"), notes="S8 (#1394's second review): the decline's report survives " "group's rebuilt read where the chain took a member the " - "read had picked; 3175314d read suffix 'MD MA DE'"), + "read had picked; 2.4.0 through 3.1.0 read family 'VAN', suffix 'MD MA DE'; 1.4.0 through 2.3.0 read these fields"), Case("md_in_a_mixed_case_maiden_clause_keeps_the_run", "JOHN SMITH née Ann Lee MD Jones", {"given": "JOHN", "family": "SMITH", "maiden": "Ann Lee", @@ -18066,7 +18070,7 @@ def _check_cjk_shape_purity(self) -> None: classification="fix(#602)", ambiguities=("suffix-or-name", "suffix-or-name"), notes="boundary: a maiden marker behind it is no name word; " - "read as on 3175314d"), + "read as 2.4.0 through 3.1.0 read it"), Case("md_in_capitals_before_a_caseless_word_starts_the_run", "محمد علي MD حسن", {"given": "محمد", "family": "علي", "suffix": "MD حسن"}, @@ -18074,7 +18078,7 @@ def _check_cjk_shape_purity(self) -> None: ambiguities=("suffix-or-name",), notes="boundary: a Latin MD in a name of a script with no case " "shares no case with it, so its capitals stay the " - "credential's; read as on 3175314d"), + "credential's; read as 2.4.0 through 3.1.0 read it"), Case("wm_dotted_trailing_is_a_name_word", "John Smith Wm.", {"given": "John", "middle": "Smith", "family": "Wm."}, notes="H5 read a listed `wm` as a title here from 2.3.0 " diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index 5f1e194fa..45dcb2b70 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -2217,3 +2217,87 @@ def test_words_finds_a_spelling_of_several_by_any_word_it_names() -> None: assert "md" not in lexicon.words(kind="given", same_as=["muhammad", "mohamad"]) assert lexicon.words(kind="given", same_as="charles") == ("chas",) + + +@pytest.mark.parametrize("prop, kind, word", [ + ("completes", "bound_second", "ذو"), + ("completed_by", "bound_given", "الله"), +]) +def test_a_pair_list_given_a_bare_string_offers_a_list_that_runs( + prop: str, kind: str, word: str) -> None: + with pytest.raises(TypeError) as refused: + Lexicon.default().add("zzend", kind=kind, **{prop: word}) + offered = str(refused.value).split(f"e.g. {prop}=", 1)[1].split(", got")[0] + added = Lexicon.default().add("zzend", kind=kind, + **{prop: eval(offered)}) + assert [dict(r.properties)[prop] for r in added.readings_of("zzend")] == [ + tuple(sorted(eval(offered)))] + + +def test_completed_by_none_clears_the_list_the_message_offers_to_clear() -> None: + # the empty-list refusal offers `completed_by=None` to clear a list + # the word's reading has; run what it offers on a word that ships + # one, and read the clearing in a parse (rules/P12) + with pytest.raises(ValueError, match="completed_by=None") as refused: + Lexicon.default().add("عبد", kind="bound_given", completed_by=[]) + offered = str(refused.value).split("write ", 1)[1].split(" to clear")[0] + assert offered == "completed_by=None" + # what it clears to: the word keeps P5's join, but no listed word + # completes it any more + assert str(refused.value).endswith( + "which leaves no listed word completing it") + shipped = [dict(r.properties) for r in + Lexicon.default().readings_of("عبد") + if r.kind == "bound_given"] + assert shipped and all(p.get("completed_by") for p in shipped) + assert Parser().parse("سامر نور عبد الله").family == "عبد الله" + cleared = Lexicon.default().add("عبد", kind="bound_given", + completed_by=None) + assert [(r.kind, r.properties) for r in cleared.readings_of("عبد")] == [ + ("bound_given", ())] + assert Parser(lexicon=cleared).parse("سامر نور عبد الله").family == "الله" + + +def _article_rows() -> list[tuple[str, str]]: + from nameparser._reading_index import CATEGORY + rows = [(kind, "an" if kind[:1] in "aeiou" or kind == "honorific" + else "a") for kind in sorted(CATEGORY)] + assert any(a == "an" for _, a in rows) and any(a == "a" for _, a in rows) + return rows + + +@pytest.mark.parametrize("kind, article", _article_rows()) +def test_a_refused_property_names_the_kind_with_its_article( + kind: str, article: str) -> None: + # every kind beginning with a vowel, and honorific, whose h is + # silent, reads "an"; the rest "a" + with pytest.raises(ValueError, + match=f"^{article} {kind} reading takes "): + Lexicon.empty().add("zzq", kind=kind, zzprop=True) # type: ignore[call-arg] + + +def _attached_and_phrase_rows() -> tuple[list[tuple[str, str]], + list[tuple[str, str]]]: + from nameparser._reading_index import CATEGORY + rows = _article_rows() + attached = [(k, a) for k, a in rows + if CATEGORY[k] in ("title", "suffix")] + phrase = [(k, a) for k, a in rows if k != "birth_marker" + and CATEGORY[k] not in ("familiar", "spelling")] + assert attached and phrase + return attached, phrase + + +@pytest.mark.parametrize("kind, article", _attached_and_phrase_rows()[0]) +def test_an_attached_side_names_the_kind_with_its_article( + kind: str, article: str) -> None: + with pytest.raises(ValueError, + match=f"^attached on {article} '{kind}' reading"): + Lexicon.empty().add("zzq", kind=kind, attached="sideways") + + +@pytest.mark.parametrize("kind, article", _attached_and_phrase_rows()[1]) +def test_a_phrase_names_the_kind_with_its_article( + kind: str, article: str) -> None: + with pytest.raises(ValueError, match=f"match as {article} {kind}:"): + Lexicon.empty().add("zzq yyq", kind=kind) diff --git a/tests/v2/test_suggest.py b/tests/v2/test_suggest.py index 0fce43037..b0e68309c 100644 --- a/tests/v2/test_suggest.py +++ b/tests/v2/test_suggest.py @@ -3682,3 +3682,81 @@ def test_a_switch_not_weighed_says_why_and_casts_no_vote( evidence.contested, evidence.no_evidence, evidence.by_signal ) == (False, 0, 0, 0, len(names), ()) assert not any(Signal.FIRST_SURNAME in name.votes for name in s.names) + + +#: A value of each setting a signal votes on, for SettingEvidence rows +_SETTING_VALUES: dict[str, object] = { + "name_order": FAMILY_FIRST, "two_family_names": True, + "patronymic_rules": frozenset({PatronymicRule.EAST_SLAVIC})} + + +def _non_order_signals() -> list[tuple[Signal, object, str, object]]: + from nameparser._suggest import _SETTING_OF + bad = {"two_family_names": 1, "patronymic_rules": "east-slavic"} + rows = [(signal, bad[setting], setting, _SETTING_VALUES[setting]) + for signal, setting in _SETTING_OF.items() + if setting != "name_order"] + assert rows + return rows + + +@pytest.mark.parametrize("signal, bad, setting, value", _non_order_signals()) +def test_a_refused_vote_offers_its_owners_shape_and_the_code_runs( + signal: Signal, bad: object, setting: str, value: object) -> None: + # a NameEvidence vote is a mapping entry, a SettingEvidence row a + # triple: each refusal offers its own owner's spelling (the row's + # offered a mapping until the 3.2 prose sweep), and that spelling + # is accepted where the refused one was + names = {"Signal": Signal, "PatronymicRule": PatronymicRule} + with pytest.raises(TypeError) as name_refused: + NameEvidence("Zzana Qqmoreno", {signal: bad}) # type: ignore[dict-item] + entry = eval(str(name_refused.value).rsplit("pass e.g. ", 1)[1], names) + NameEvidence("Zzana Qqmoreno", entry) + with pytest.raises(TypeError) as row_refused: + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + ((signal, bad, 2),)) # type: ignore[arg-type] + row = eval(str(row_refused.value).rsplit("pass e.g. ", 1)[1], names) + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + (row,)) + + +def _settings_voted_on() -> list[str]: + from nameparser._suggest import _SETTING_OF + settings = sorted(set(_SETTING_OF.values())) + assert settings + return settings + + +#: The settings ``Parser.suggest`` returns evidence for: the three a +#: signal votes on, and two it decides with no signal's row +_EMITTED = (*_settings_voted_on(), "initials_as_family", "capitals_as_family") + + +@pytest.mark.parametrize("setting", _EMITTED) +def test_a_refused_by_signal_is_offered_code_its_own_setting_takes( + setting: str) -> None: + # a row that is no triple, and a by_signal that is no iterable, are + # each offered code the evidence's own setting accepts: a row whose + # signal votes on it, or no row where no signal does (the name_order + # row was offered for every setting until the 3.2 prose sweep) + from nameparser._suggest import _SETTING_OF + value = _SETTING_VALUES.get(setting, True) + names = {"Signal": Signal, "PatronymicRule": PatronymicRule, + "FAMILY_FIRST": FAMILY_FIRST} + voted_on = setting in set(_SETTING_OF.values()) + with pytest.raises(TypeError) as refused_row: + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + ("x",)) # type: ignore[arg-type] + if voted_on: + row = eval(str(refused_row.value).rsplit("pass e.g. ", 1)[1], names) + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + (row,)) + else: + assert str(refused_row.value).endswith("pass by_signal=()") + with pytest.raises(TypeError) as refused_rows: + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + 5) # type: ignore[arg-type] + offered = str(refused_rows.value).rsplit("pass e.g. ", 1)[1] + for code in offered.split(" or "): + SettingEvidence(setting, value, True, 2, 0, 0, 0, # type: ignore[arg-type] + eval(code, names)) diff --git a/tools/differential/README.md b/tools/differential/README.md index af9f006a0..93f0451cd 100644 --- a/tools/differential/README.md +++ b/tools/differential/README.md @@ -420,7 +420,7 @@ uv run python tools/differential/config_diff.py score default plain:ES --switche uv run python tools/differential/match_diff.py --base ../master-checkout ``` -**Measuring a change to the group suggester.** `Parser.suggest` moves no parse either, so its check is `suggest_measure.py`: it draws groups of 2 to 200 names (`--sizes`, `--trials`, `--seed`) from populations whose order is known because each name is composed from the boxes its filer typed it into -- PatentsView inventors by country (and, since #1364, the non-CJK inventors whose given box opens with a word PatentsView's boxes write as a family name at least as often, `pv-surname-given`, or with a word of the ORCID surname table, `pv-listed-given`), UK company filers (`psc-individuals`) by nationality, Czech candidates, Vietnamese names, the Russian inventors whose given box holds a patronymic (`pv-RU-patronymic`, the list the East Slavic rule is decided on), ORCID's bylines (and the ones written two or three joined initials first) and the ORCID holders who typed one box wholly in capitals (and the ones from China, Korea, Vietnam and Taiwan, `orcid-famcaps-ea`, and the ones whose family box is two or three letters), all local corpora -- writes each group given-first and family-first, and prints the share of groups whose suggested `name_order` writes the family at the end the group was written with, under a given-first and a family-first base. The two rows where the group is written in its base's own order are the anti-goal (decisions/group-suggestion): a suggestion must not move a group the base already reads right, and the thresholds in `nameparser/_suggest.py` were chosen so that neither falls below 95% at any size, save `orcid-givcaps`' two, names typed with the given name in capitals (`ANNA Smith`), which the capitals signal reads the wrong way round by design (decisions/group-suggestion, 2026-11-12 CAPITALS), `pv-listed-given`'s two, a list of nothing but given names the ORCID surname table lists (`Cooper`, `Burke`), which that table reads the wrong way round, a cost left open (decisions/group-suggestion, 2026-11-19 #1364), and `orcid-byline-joined`'s given-first row at 50 and 100 names, and at 200 until #1357 (bylines written `AM Hoy` and nothing else), one of two cuts added with #1355 to hold the short capitals words in view and explained in that file's 2026-11-14 #1355 entry; the other, `orcid-famcaps-short` (`Zhi LI`), left the list with #1397 (that file's 2026-11-14 #1397 entry). Under each population it prints the groups that decided the East Slavic rule and those that decided `initials_as_family` (rules/O8); under the order table, the share of groups deciding `capitals_as_family` (rules/O9), and of those deciding `two_family_names` (rules/O6), for every population where any group did, and `--base` lists those cells too. The `orcid-span-CC` populations (#1452: ORCID holders of each of `SPAN_COUNTRIES`, the name composed from their two boxes) add, written given first under a given-first base, whole names read right against the boxes under the suggestion and under the base, and the bare switch off and on over a sample. It also prints each population's votes per name (right, wrong, contested, none) and per signal, with `--wrong-words N` each signal's commonest words in a wrong vote; the opensanctions-parliaments table of the 2026-11-10 TURKIC entry; and every parliament list's own suggestion, under the two bases and `FAMILY_FIRST_GIVEN_LAST`, beside the order it was read by eye to write. Its draws run under the two bases only, so what a suggestion does under `FAMILY_FIRST_GIVEN_LAST`, and the East Slavic rule beside `capitals_as_family`, are held by tests (decisions/group-suggestion, 2026-11-15 #1356). `--set NAME=VALUE` tries another threshold without editing the module, and is the harness's proof that it can report a difference: `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000 --set _MIN_TWO_FAMILY_VOTES=1000000` decides nothing (the second holds the patronymic rule, which decides a given-first order of its own, save where #1356 keeps the family-first base's, the third the letters signal's `initials_as_family`, which the two vote counts leave free to decide, and the fourth `two_family_names`, #1452), so every group written against its base reads 0% (all 60 such rows, at all eight sizes, on 2026-11-15, measured with the first two). `--checks` prints, instead of the tables, the per-name checks the decisions entry quotes (the short romanized surnames' wrong votes, names ending in a bare non-ASCII letter, and, over the groups holding enough names of one patronymic rule to decide it, whether the patronymic share's denominator decides any differently without the contested names). `--base ` measures another tree in a child process and lists the cells that moved, the populations whose count of groups deciding the East Slavic rule moved, and the parliament tables' rows that moved. A source present but yielding no names, and a population or parliament list a present source holds none of, prints a note. A whole run with every source fetched took 20s with `--jobs 12` on one 12-CPU machine (2026-11-10, sizes 2 to 200; a machine-bound figure). +**Measuring a change to the group suggester.** `Parser.suggest` moves no parse either, so its check is `suggest_measure.py`: it draws groups of 2 to 200 names (`--sizes`, `--trials`, `--seed`) from populations whose order is known because each name is composed from the boxes its filer typed it into -- PatentsView inventors by country (and, since #1364, the non-CJK inventors whose given box opens with a word PatentsView's boxes write as a family name at least as often, `pv-surname-given`, or with a word of the ORCID surname table, `pv-listed-given`), UK company filers (`psc-individuals`) by nationality, Czech candidates, Vietnamese names, the Russian inventors whose given box holds a patronymic (`pv-RU-patronymic`, the list the East Slavic rule is decided on), ORCID's bylines (and the ones written two or three joined initials first) and the ORCID holders who typed one box wholly in capitals (and the ones from China, Korea, Vietnam and Taiwan, `orcid-famcaps-ea`, and the ones whose family box is two or three letters), all local corpora -- writes each group given-first and family-first, and prints the share of groups whose suggested `name_order` writes the family at the end the group was written with, under a given-first and a family-first base. The two rows where the group is written in its base's own order are the anti-goal (decisions/group-suggestion): a suggestion must not move a group the base already reads right, and the thresholds in `nameparser/_suggest.py` were chosen so that neither falls below 95% at any size, save `orcid-givcaps`' two, names typed with the given name in capitals (`ANNA Smith`), which the capitals signal reads the wrong way round by design (decisions/group-suggestion, 2026-11-12 CAPITALS), `pv-listed-given`'s two, a list of nothing but given names the ORCID surname table lists (`Cooper`, `Burke`), which that table reads the wrong way round, a cost left open (decisions/group-suggestion, 2026-11-19 #1364), and `orcid-byline-joined`'s given-first row at 50 and 100 names, and at 200 until #1357 (bylines written `AM Hoy` and nothing else), one of two cuts added with #1355 to hold the short capitals words in view and explained in that file's 2026-11-14 #1355 entry; the other, `orcid-famcaps-short` (`Zhi LI`), left the list with #1397 (that file's 2026-11-14 #1397 entry). Under each population it prints the groups that decided the East Slavic rule and those that decided `initials_as_family` (rules/O8); under the order table, the share of groups deciding `capitals_as_family` (rules/O9), and of those deciding `two_family_names` (rules/O6), for every population where any group did, and `--base` lists those cells too. The `orcid-span-CC` populations (#1452: ORCID holders of each of `SPAN_COUNTRIES`, the name composed from their two boxes) add, written given first under a given-first base, whole names read right against the boxes under the suggestion and under the base, and the bare switch off and on over a sample. It also prints each population's votes per name (right, wrong, contested, none) and per signal, with `--wrong-words N` each signal's commonest words in a wrong vote; the opensanctions-parliaments table of the 2026-11-10 TURKIC entry; and every parliament list's own suggestion, under the two bases and `FAMILY_FIRST_GIVEN_LAST`, beside the order it was read by eye to write. Its draws run under the two bases only, so what a suggestion does under `FAMILY_FIRST_GIVEN_LAST`, and the East Slavic rule beside `capitals_as_family`, are held by tests (decisions/group-suggestion, 2026-11-15 #1356). `--set NAME=VALUE` tries another threshold without editing the module, and is the harness's proof that it can report a difference: `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000 --set _MIN_TWO_FAMILY_VOTES=1000000` decides nothing (the second holds the patronymic rule, which decides a given-first order of its own, save where #1356 keeps the family-first base's, the third the letters signal's `initials_as_family`, which the two vote counts leave free to decide, and the fourth `two_family_names`, #1452), so every group written against its base reads 0% (all 60 such rows, at all eight sizes, on 2026-11-15, measured with the first two). `--checks` prints, instead of the tables, the per-name checks the decisions entry quotes (the short romanized surnames' wrong votes, names ending in a bare non-ASCII letter, and, over the groups holding enough names of one patronymic rule to decide it, whether the patronymic share's denominator decides any differently without the contested names). `--base ` measures another tree in a child process and lists the cells that moved, the populations whose count of groups deciding the East Slavic rule or `initials_as_family` moved, the `capitals_as_family` and `two_family_names` cells and the span scores that moved, and the parliament tables' rows that moved. A source present but yielding no names, and a population or parliament list a present source holds none of, prints a note. A whole run with every source fetched took 20s with `--jobs 12` on one 12-CPU machine (2026-11-10, sizes 2 to 200, before #1364's and #1452's populations joined; a machine-bound figure). ``` uv run python tools/differential/suggest_measure.py @@ -628,7 +628,7 @@ data can. and say why in the commit. Run it without `--record` for per-role agreement counts. Nothing is special-cased: an unnatural rendering or a modelling difference (CLDR's `さん` title is a suffix here) simply stays a recorded disagreement, which makes the record a measured worklist as well as a guard. -A second view measures the locale packs (#672). `LOCALE_FILES` in `cldr_agreement.py` maps each CLDR file to the pack for its language (`zh`, `zh_Hant`, `yue`, `yue_Hans` → `ZH`; `ja` → `JA`; `ne` → `NE`; `ru` → `RU`; `tr`, `az` → `TR_AZ`; `cs`, `sk`, `sl`, `hr`, `ga`, `gd`, `es`, `vi`, `mn`, `ar`, `he` → the pack of that name; `pt` → `PT_BR`; `hi`, `hi_Latn` → `HI`; `bn` → `BN`); those renderings are parsed with `parser_for(pack)`, over the same `FAMILY_FIRST` base where CLDR's order is surnameFirst, and their disagreements go to `cldr_agreement_locales.json`, ratcheted per pack by the same test. The native-script Wikidata source's strata of a pack's language are mapped by `NATIVE_LABELS` (`zh-cn`, `zh-tw` → `ZH`; `ja-jp` → `JA`; `ne-np` → `NE`; `hi-in` → `HI`; `bn-in`, `bn-bd` → `BN`), since their file is a QID that names no language, and the view parses them the same way into `wikidata_native_agreement_locales.json`. Each source's pack is read from its own rendering key (`locale_sources()`: CLDR's file, the native source's stratum), so a recorded rendering that is gone is still checked by its pack. The summary prints, per pack, how many of its renderings agree in every role under the default parser and under the pack, so a pack PR shows what it moved on its own language. A new pack adds its files to `LOCALE_FILES`, or its name to `NO_CLDR`; the test fails on a pack in neither. The modelling differences stay recorded here too: a pack is not meant to agree with CLDR where the models differ by design. +A second view measures the locale packs (#672). `LOCALE_FILES` in `cldr_agreement.py` maps each CLDR file to the pack for its language (`zh`, `zh_Hant`, `yue`, `yue_Hans` → `ZH`; `ja` → `JA`; `ne` → `NE`; `ru` → `RU`; `tr`, `az` → `TR_AZ`; `cs`, `sk`, `sl`, `hr`, `ga`, `gd`, `es`, `vi`, `mn`, `ar`, `he`, `nl`, `ms`, `my` → the pack of that name (CLDR's `my` is in Burmese script, which `MY`'s Latin readings do not reach); `pt` → `PT_BR`; `hi`, `hi_Latn` → `HI`; `bn` → `BN`); those renderings are parsed with `parser_for(pack)`, over the same `FAMILY_FIRST` base where CLDR's order is surnameFirst, and their disagreements go to `cldr_agreement_locales.json`, ratcheted per pack by the same test. The native-script Wikidata source's strata of a pack's language are mapped by `NATIVE_LABELS` (`zh-cn`, `zh-tw` → `ZH`; `ja-jp` → `JA`; `ne-np` → `NE`; `hi-in` → `HI`; `bn-in`, `bn-bd` → `BN`), since their file is a QID that names no language, and the view parses them the same way into `wikidata_native_agreement_locales.json`. Each source's pack is read from its own rendering key (`locale_sources()`: CLDR's file, the native source's stratum), so a recorded rendering that is gone is still checked by its pack. The summary prints, per pack, how many of its renderings agree in every role under the default parser and under the pack, so a pack PR shows what it moved on its own language. A new pack adds its files to `LOCALE_FILES`, or its name to `NO_CLDR`; the test fails on a pack in neither. The modelling differences stay recorded here too: a pack is not meant to agree with CLDR where the models differ by design. **The GND source.** `build_gnd_corpus.py` writes the GND's name parts in CLDR's field vocabulary (`forename` → `given`, `prefix` → `surname-prefix` with a one-word `surname` as `surname-core`, any other family → `surname` whole, `counting` → `generation`, and a `personalName` -- a person entered under the whole name, with no surname -- as `given` alone, so the family is expected empty), so `cldr_agreement.py` compares `gnd_fields.jsonl` by the same rules and records its disagreements in `gnd_agreement.json`, ratcheted by the same test. The locale view does not read it: no pack covers its names. A composed rendering says so (`composed: true`); where a particle is glued to the surname (`d'Arenberg`, `al-Ǧaʿfarī`) the composed line states the glued word as a whole `surname`, since the comparison matches fields word by word, and the index form, where the particle is a word of its own, keeps the split. A family with no `prefix`, or with a surname of several words, is stated whole for the same kind of reason: GND does not split a particle inside a surname (`Vélez de Guevara`, `Zuylen van Nijevelt`), so what it leaves unsplit means "not stated", not "no particle", and only `family` is compared there. Raw lobid responses are cached outside the tree, in a `gnd/` directory under `$NAMEPARSER_TOOLS_CACHE` (default `~/.cache/nameparser-tools`); `--refresh` fetches them again. The build stops before writing anything when a stratum falls below its floor, a query matches nothing, or a pool pages short, so a lobid change fails it rather than shrinking the corpus; `--record` prints, per source, how many changes of each kind it accepts. diff --git a/tools/differential/cldr_agreement.py b/tools/differential/cldr_agreement.py index dd0216206..e7b96aceb 100644 --- a/tools/differential/cldr_agreement.py +++ b/tools/differential/cldr_agreement.py @@ -160,7 +160,7 @@ LOCALE_FILES = {"zh": "ZH", "zh_Hant": "ZH", "yue": "ZH", "yue_Hans": "ZH", "ja": "JA", "ne": "NE", "ru": "RU", "tr": "TR_AZ", "az": "TR_AZ", "cs": "CS", "sk": "SK", "sl": "SL", "hr": "HR", - # CLDR's pt is Brazilian Portuguese (pt_PT is its own file) + # CLDR's pt is Brazilian Portuguese (CLDR 48 has no pt_PT file) "ga": "GA", "gd": "GD", "pt": "PT_BR", "es": "ES", # hi_Latn is the romanized Hindi the pack's Latin readings are for "hi": "HI", "hi_Latn": "HI", "bn": "BN", "vi": "VI", diff --git a/tools/differential/local_agreement.py b/tools/differential/local_agreement.py index fe91e9bae..1a3f1c09d 100644 --- a/tools/differential/local_agreement.py +++ b/tools/differential/local_agreement.py @@ -6,7 +6,8 @@ and each field is compared with the box the filer typed it into (`psc-individuals`' title, forename, middle name and surname boxes; `orcid-researchers`' given-names box, holding the middle names too, and -family-name box, typed by the holder; `cz-candidates`' title before the +family-name box, typed by the holder; `patentsview-inventors`' first-name +and last-name boxes, split by the applicant's filer; `cz-candidates`' title before the name, given names, surname and title after it; and the two Vietnamese corpora, whose family, middle and given names no one filed: `uit-vinames` and `vn-assembly` state a name whole, in the Vietnamese order, and their diff --git a/tools/differential/local_ctgov.py b/tools/differential/local_ctgov.py index 5a3114613..5a60d4b4f 100644 --- a/tools/differential/local_ctgov.py +++ b/tools/differential/local_ctgov.py @@ -56,7 +56,7 @@ #: The version of how a record is built from what the API gives (the #: country rule, ctgov-contacts' repeat key and CTGOV_COUNTRIES's #: codes), stored in meta.json and -#: required on load: bump it with any change to either, so a corpus read +#: required on load: bump it with any change to any of them, so a corpus read #: the old way is refused rather than read. 1: the country (#1451); a #: corpus fetched before it holds no "country" and is refused too. CTGOV_READ_VERSION = 1 diff --git a/tools/differential/suggest_measure.py b/tools/differential/suggest_measure.py index f149f4c1a..ad93023df 100644 --- a/tools/differential/suggest_measure.py +++ b/tools/differential/suggest_measure.py @@ -1,18 +1,21 @@ """Measure Parser.suggest on groups of names whose written order is known. `Parser.suggest(names)` reads a group of names a caller declares to share -one convention and suggests a `name_order` (and `patronymic_rules`). Its +one convention and suggests a `name_order` (and `patronymic_rules`, +`initials_as_family`, `capitals_as_family` and `two_family_names`). Its decision rule (`_suggest._MIN_VOTES`, `_MIN_SHARE`, `_MIN_ORDER_GROUP_SHARE`, `_MIN_PATRONYMIC_SHARE`, `_MIN_PATRONYMIC_VOTES`, the trailing-initial signal's `_MIN_TRAILING_NAMES` and `_MIN_TRAILING_SHARE`, and for -`initials_as_family`, `_MIN_RUN_NAMES` and `_MIN_RUN_SHARE`) and its word tables +`initials_as_family`, `_MIN_RUN_NAMES` and `_MIN_RUN_SHARE`, for +`capitals_as_family`, `_MIN_CAPITALS_LETTERS`, and for `two_family_names`, +`_MIN_TWO_FAMILY_VOTES` and `_MIN_TWO_FAMILY_SHARE`) and its word tables (`config/_order_names.py`, written by tools/vocab/order_names.py) were chosen with this tool, and the figures quoted for them in `suggest`'s docstring and docs/design/decisions/group-suggestion.md are its output. uv run python tools/differential/suggest_measure.py uv run python tools/differential/suggest_measure.py --sizes 5,10 --trials 100 - uv run python tools/differential/suggest_measure.py --set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 + uv run python tools/differential/suggest_measure.py --set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000 --set _MIN_TWO_FAMILY_VOTES=1000000 uv run python tools/differential/suggest_measure.py --base THE POPULATIONS, from the local corpora in $NAMEPARSER_TOOLS_CACHE @@ -45,7 +48,11 @@ own boxes write as a family name at least as often (`Cruz`, `Moreno`; not a romanized surname, `Lee`, whose cost is as old as its table), and `pv-listed-given`, the same inventors whose given box opens with a word -of the ORCID surname table, each read from this script's checkout and +of the ORCID surname table, and `orcid-span-CC`, ORCID holders of each +of SPAN_COUNTRIES (SPAN_FOR, the Spanish- and Portuguese-speaking +countries `two_family_names` is for; SPAN_NOT, where it must not be +suggested; SPAN_UNSEEN; and the US), both boxes filled and no comma in +either (#1452), each read from this script's checkout and less a record whose family box opens with a listed given name (boxes likely swapped): the lists a surname table moves the wrong way (#1364; the Spanish- and Portuguese-speaking countries and filers, the Filipino, @@ -83,7 +90,13 @@ decided it the share of its names whose family the suggested parser reads as the box (case folded), with the switch and with the same suggestion less it; `--base` lists every such cell that moved. `--set _MIN_CAPITALS_LETTERS=1000000` decides it in no -group. +group. Then the share of groups deciding `two_family_names` (rules/O6), +where any group did, and for each `orcid-span-CC` population, written +given first under the given-first base at each size up to SPAN_SCORED, +the share of whole names read right against the boxes under the +suggestion and under the base, and the bare switch off and on over +SIGNAL_NAMES names; `--base` lists every such cell that moved. `--set +_MIN_TWO_FAMILY_VOTES=1000000` decides it in no group. THE SIGNALS: per population and written order, over at most SIGNAL_NAMES names, the per-NAME order votes (`suggest`'s unit: right, wrong, @@ -124,17 +137,22 @@ checkout without that threshold runs its own rule, and the comparison says so); it is also the harness's proof that it can report a difference: `--set -_MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000` decides nothing -(the first holds the order, the second the patronymic rule, which -decides a given-first order of its own, save where #1356 keeps the -family-first base's), so every family-first group under the given-first +_MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set +_MIN_RUN_NAMES=1000000 --set _MIN_TWO_FAMILY_VOTES=1000000` decides +nothing (the first holds the order and `capitals_as_family`, the second +the patronymic rule, which decides a given-first order of its own, save +where #1356 keeps the family-first base's, the third the letters +signal's `initials_as_family`, the fourth `two_family_names`, #1452), so every family-first group under the given-first base must read 0% (and every given-first group under the family-first base). `--base` runs the same measurement against another checkout in a child process and lists every cell that moved, every -population whose count of groups deciding the East Slavic rule moved, -and every TURKIC row and parliament suggestion that moved. +population whose count of groups deciding the East Slavic rule or +`initials_as_family` moved, every `capitals_as_family` and +`two_family_names` cell and span score that moved, and every TURKIC row +and parliament suggestion that moved. -Runtime, measured 2026-11-10 on a 12-CPU machine with every source +Runtime, measured 2026-11-10 on a 12-CPU machine, before #1364's and +#1452's populations and the whole-name scores joined, with every source fetched and the defaults (sizes 2-200, 300 trials, --jobs 12): 20s wall clock, 6s of it reading the corpora in one process; with --base, twice that. diff --git a/tools/es_given_names.py b/tools/es_given_names.py index 534cf69f8..157dbc079 100644 --- a/tools/es_given_names.py +++ b/tools/es_given_names.py @@ -302,7 +302,8 @@ def load_surnames(refresh: bool) -> list[tuple[str, int]]: def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser = argparse.ArgumentParser( + description=" ".join(__doc__.split("\n\n")[0].split())) parser.add_argument("--list", choices=sorted(LISTS), default="es", help="the list to build, by its pack's language tag") parser.add_argument("--write", action="store_true", diff --git a/tools/pt_given_names.py b/tools/pt_given_names.py index 12e282789..531fce242 100644 --- a/tools/pt_given_names.py +++ b/tools/pt_given_names.py @@ -37,7 +37,8 @@ measured choices (decisions/O6, 2026-11-19): a change to either is a cutoff change, decided against the same per-country measurement. Every word the cut keeps was read by hand before the list shipped; -REMOVED holds each word that reading took out, with why. +REMOVED holds each word that reading took out, with why (none on +2026-11-19). Each listed word written with ç is also listed with c where that spelling passes the same share test over every use the c stands for, @@ -208,7 +209,8 @@ def particles() -> set[str]: def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser = argparse.ArgumentParser( + description=" ".join(__doc__.split("\n\n")[0].split())) parser.add_argument("--write", action="store_true", help="rewrite the generated block in the list's module") parser.add_argument("--min-uses", type=int, default=MIN_USES) diff --git a/tools/vocab/build.py b/tools/vocab/build.py index 79df06107..18220b9c6 100644 --- a/tools/vocab/build.py +++ b/tools/vocab/build.py @@ -4,7 +4,7 @@ Usage:: - uv run python tools/vocab/build.py # rewrite both modules + uv run python tools/vocab/build.py # rewrite the three modules uv run python tools/vocab/build.py --check # exit 1 if any is stale Either exits 2, printing the failed check, when the vocabulary fails one @@ -1785,7 +1785,7 @@ def file_tags(pool: Pool) -> list[str]: def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--check", action="store_true", - help="exit 1 if the committed module is stale " + help="exit 1 if a committed module is stale " "(2 if the vocabulary fails a check, 3 on an " "internal error)") args = ap.parse_args(argv) diff --git a/tools/vocab/familiar_wikidata.py b/tools/vocab/familiar_wikidata.py index dab19c5f9..e039c7e64 100644 --- a/tools/vocab/familiar_wikidata.py +++ b/tools/vocab/familiar_wikidata.py @@ -61,7 +61,7 @@ ~/.cache/nameparser-tools) under FETCH_DIR, named by the query's digest, and asks the query service again only for an answer it does not hold; `pairs` reads the kept answers alone, refusing to run on a -missing one, and writes CANDIDATES_FILE beside them (a file of its own +missing one, and writes CANDIDATES_FILE in the cache folder above them (a file of its own for `--country`). The requests name no person or project (USER_AGENT). The candidates hold given names, counts and country codes, no person. """ diff --git a/tools/vocab/order_names.py b/tools/vocab/order_names.py index dd1a2c033..eb7472ecc 100644 --- a/tools/vocab/order_names.py +++ b/tools/vocab/order_names.py @@ -5,7 +5,7 @@ surname at one end of the name and not at the other says the family name is written at that end, and a common given name at one end and not the other says the given name is. The tables, in -``nameparser/config/_order_names.py``, hold folded spellings: the generated block is the Hanyu Pinyin of every +``nameparser/config/_order_names.py``, hold folded spellings: the first generated block, ``PINYIN``, is the Hanyu Pinyin of every single-character surname ``locales.ZH`` lists, from Wikidata (CC0): of each family-name item labelled with the character, every reading a Hanyu Pinyin statement gives (a transliteration, P2440, qualified as @@ -16,12 +16,12 @@ block read Unihan's first ``kMandarin`` reading (Unicode License v3), which is the character's commonest reading rather than its surname's (曾 ceng for the surname Zeng). The Wade-Giles, Korean and -Vietnamese lists are kept by hand above the generated block, hand-curated +Vietnamese lists are kept by hand above the generated blocks, hand-curated and unchecked against any ranking (see the note in nameparser/config/_order_names.py). - uv run python tools/vocab/order_names.py # print the block - uv run python tools/vocab/order_names.py --write # rewrite it + uv run python tools/vocab/order_names.py # print the blocks + uv run python tools/vocab/order_names.py --write # rewrite them uv run python tools/vocab/order_names.py --refresh # ask Wikidata again The second generated block, ``COMMON_GIVEN``, is the given names the @@ -48,7 +48,7 @@ (tools/differential/local_corpora.py), checked whole against its recorded sha256, and it writes nothing where a block falls below its floor (``MIN_PINYIN``, -``MIN_GIVEN``) or a word lands in both tables. +``MIN_GIVEN``) or a word lands in two tables. The third generated block, ``COMMON_SURNAMES``, is the mirror of the second (#1364): every word ORCID's holders typed in the family-name box @@ -455,7 +455,7 @@ def check_tables(pinyin: set[str], given: set[str], def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0]) parser.add_argument("--write", action="store_true", - help="rewrite the generated block") + help="rewrite the generated blocks") parser.add_argument("--refresh", action="store_true", help="ask Wikidata again") args = parser.parse_args(argv)