diff --git a/AGENTS.md b/AGENTS.md index ff01275af..6e6065c97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,7 +263,7 @@ Latin-script input is never touched by any of this: "Kim Min-jun" is genuinely o ### Vocabulary (`nameparser/vocab/`) and the configuration layer (`nameparser/config/`) -**The default vocabulary is written per word, in TOML, and compiled.** `nameparser/vocab/.toml` holds one file per BCP 47 language tag, each `[[word]]` entry a `text` and its readings keyed by kind. What a file means, how an entry is built, the kinds and properties with the set each compiles into, exclusions, bearer counts and the steps for adding a word are in `nameparser/vocab/README.md`, the reference for anyone editing the TOML; `tests/v2/test_vocab.py` holds its kind, property, derived-marker and reserved-name tables to the names `build.py` accepts and the sets it compiles, so read it rather than restating it here. The parser never reads the TOML: `tools/vocab/build.py` runs the build checks that replaced the modules' import-time asserts (its docstring numbers them), turns every reading into an index row with its file's tag, and writes the rows, and every file's tag (`FILES`, a file holding only exclusions included, for a strict choice to name), as the committed reading index `nameparser/config/_index.py` (#753, phase 3a) and, compiled, as the committed `nameparser/config/_compiled.py`, frozenset literals one entry per line; the build never reads `_index.py` back. A file a shipped pack reads may also hold a `[rules]` table, each key a `Policy` field (`patronymic_rules`, `name_order`, `two_family_names`, `two_given_names`, `initials_as_family`), which the build checks against its `RULE_KEYS` and `PACK_RULES` and writes as `nameparser/config/_rules.py`; `_locale.rules_patch(tag)` turns a file's table into the `PolicyPatch` a pack carries, RU's and TR_AZ's from `ru.toml` and `tr.toml`, and the `two_family_names` of ES, CS and SK from `es.toml`, `cs.toml` and `sk.toml`, and ES_AR's from `es.toml`, a country pack reading its language's table (#754, 4f; decisions/vocabulary-model's 2026-10-29 4f entry), and VI's `name_order` from `vi.toml` (#1108), and NE's `initials_as_family` from `ne.toml` (#1254). The compiler is `nameparser/_reading_index.py`'s `compile_readings`, with the kind and property tables it reads (`CATEGORY`, `BEHAVIORAL`, `GATED_WORDS`), so the build and a choice of languages compile alike: `Locale.languages` (3.0, phase 3b) is a choice of BCP 47 tags, which `parser_for` unions across its packs and base's recorded choice and records on the `Lexicon` (`Lexicon.languages`, 3.0's 4i-c), the lexicon compiling its base's readings through `choose` and its own edits after them, `choose` selecting the readings (a chosen file's `default = false` ones on; on a word a chosen file holds a vocabulary reading of, other files' vocabulary readings off, save `mul.toml`'s and `und.toml`'s; a chosen conjunction's `may_be_initial` dropped; under `parser_for(..., strict=True)`, 3j, only the chosen files, `mul.toml` (#1005) and native-script words' readings as a plain choice of the same languages keeps them, name readings included, compiled, through `strict_pool`), `changed_words` deriving a choice's deviation surface which tests/v2/test_locales.py's gate reads, and `strict_ungated` the words a strict choice ungates against the plain one, which tests/v2/test_reading_index.py holds to a reviewed table (decisions/vocabulary-model, 2026-10-29 3b; 2026-10-31 #753, phase 3j); the build keeps the checks and loads that module by path, as it loads `_lexicon.py`, and `tests/v2/test_reading_index.py` holds that the index compiled with no choice is `_compiled.py` exactly. `readings_of(text)` there is the run-time reader of the index, every reading of a word with its file's tag, loaded on first call; `languages_of(text, categories)` is the reader a default parse calls for `Reading.languages` (3.0), through the lexicon's private `_files` (`_lexicon._ReadingFiles`, one per base, log and choice, hashed by identity so assemble's memo keyed by it costs no frame), which under a choice or a caller's log names the files whose reading is on in that lexicon instead (3.0's 4i-d), so the first parse that reads a word from its `Lexicon`'s vocabulary loads the index. Through 2.x each `config/` module re-exported its constants from `_compiled.py` (`TITLES = _compiled.TITLES`) under an autodoc docstring; 3.0 removed those modules (#1007, 2.8.1 warning of them), so the compiled sets are private, `Lexicon` reads them, and a caller lists a kind's words with `Lexicon.words(kind=...)`, docs/migrate.rst giving the call for each 2.x constant (a test runs every one). `tests/v2/test_vocab.py` fails when `_compiled.py` is stale, and `tests/v2/test_reading_index.py` when the index is, each naming the refresh command, and `test_vocab.py` gives every build check a mutation. The model, the phasing and what was declined: decisions/vocabulary-model. +**The default vocabulary is written per word, in TOML, and compiled.** `nameparser/vocab/.toml` holds one file per BCP 47 language tag, each `[[word]]` entry a `text` and its readings keyed by kind. What a file means, how an entry is built, the kinds and properties with the set each compiles into, exclusions, bearer counts and the steps for adding a word are in `nameparser/vocab/README.md`, the reference for anyone editing the TOML; `tests/v2/test_vocab.py` holds its kind, property, derived-marker and reserved-name tables to the names `build.py` accepts and the sets it compiles, so read it rather than restating it here. The parser never reads the TOML: `tools/vocab/build.py` runs the build checks that replaced the modules' import-time asserts (its docstring numbers them), turns every reading into an index row with its file's tag, and writes the rows, and every file's tag (`FILES`, a file holding only exclusions included, for a strict choice to name), as the committed reading index `nameparser/config/_index.py` (#753, phase 3a) and, compiled, as the committed `nameparser/config/_compiled.py`, frozenset literals one entry per line; the build never reads `_index.py` back. A file a shipped pack reads may also hold a `[rules]` table, each key a `Policy` field (`patronymic_rules`, `name_order`, `two_family_names`, `two_given_names`, `initials_as_family`), which the build checks against its `RULE_KEYS` and `PACK_RULES` and writes as `nameparser/config/_rules.py`; `_locale.rules_patch(tag)` turns a file's table into the `PolicyPatch` a pack carries, RU's and TR_AZ's from `ru.toml` and `tr.toml`, and the `two_family_names` of ES, CS and SK from `es.toml`, `cs.toml` and `sk.toml`, and ES_AR's from `es.toml`, a country pack reading its language's table (#754, 4f; decisions/vocabulary-model's 2026-10-29 4f entry), and VI's `name_order` from `vi.toml` (#1108), and NE's `initials_as_family` from `ne.toml` (#1254), and the `two_family_names` of PT_BR and PT_PT from `pt-BR.toml` and `pt-PT.toml`, country files writing a table `pt.toml` does not, `pt-PT.toml` holding nothing else (decisions/O6, 2026-11-19, #1453). The compiler is `nameparser/_reading_index.py`'s `compile_readings`, with the kind and property tables it reads (`CATEGORY`, `BEHAVIORAL`, `GATED_WORDS`), so the build and a choice of languages compile alike: `Locale.languages` (3.0, phase 3b) is a choice of BCP 47 tags, which `parser_for` unions across its packs and base's recorded choice and records on the `Lexicon` (`Lexicon.languages`, 3.0's 4i-c), the lexicon compiling its base's readings through `choose` and its own edits after them, `choose` selecting the readings (a chosen file's `default = false` ones on; on a word a chosen file holds a vocabulary reading of, other files' vocabulary readings off, save `mul.toml`'s and `und.toml`'s; a chosen conjunction's `may_be_initial` dropped; under `parser_for(..., strict=True)`, 3j, only the chosen files, `mul.toml` (#1005) and native-script words' readings as a plain choice of the same languages keeps them, name readings included, compiled, through `strict_pool`), `changed_words` deriving a choice's deviation surface which tests/v2/test_locales.py's gate reads, and `strict_ungated` the words a strict choice ungates against the plain one, which tests/v2/test_reading_index.py holds to a reviewed table (decisions/vocabulary-model, 2026-10-29 3b; 2026-10-31 #753, phase 3j); the build keeps the checks and loads that module by path, as it loads `_lexicon.py`, and `tests/v2/test_reading_index.py` holds that the index compiled with no choice is `_compiled.py` exactly. `readings_of(text)` there is the run-time reader of the index, every reading of a word with its file's tag, loaded on first call; `languages_of(text, categories)` is the reader a default parse calls for `Reading.languages` (3.0), through the lexicon's private `_files` (`_lexicon._ReadingFiles`, one per base, log and choice, hashed by identity so assemble's memo keyed by it costs no frame), which under a choice or a caller's log names the files whose reading is on in that lexicon instead (3.0's 4i-d), so the first parse that reads a word from its `Lexicon`'s vocabulary loads the index. Through 2.x each `config/` module re-exported its constants from `_compiled.py` (`TITLES = _compiled.TITLES`) under an autodoc docstring; 3.0 removed those modules (#1007, 2.8.1 warning of them), so the compiled sets are private, `Lexicon` reads them, and a caller lists a kind's words with `Lexicon.words(kind=...)`, docs/migrate.rst giving the call for each 2.x constant (a test runs every one). `tests/v2/test_vocab.py` fails when `_compiled.py` is stale, and `tests/v2/test_reading_index.py` when the index is, each naming the refresh command, and `test_vocab.py` gives every build check a mutation. The model, the phasing and what was declined: decisions/vocabulary-model. The compiled SETS are frozen since 2.2 (#293): there is no `.add()`/`.remove()` on any of them, so a default word list is changed at runtime by configuring a `Lexicon`, never by editing a constant, and the shipped default is changed by editing the TOML and rebuilding. **The five dicts are not frozen.** `_compiled.CAPITALIZATION_EXCEPTIONS` is vocabulary-shaped, private since 3.0, and read once by the cached `Lexicon.default()`, so an edit after the first parse misses it — configure the object (`dataclasses.replace(lexicon, capitalization_exceptions=...)`). `_compiled.SAME_AS` (the name match's listed spellings, a dict of dicts, below), `_compiled.SAME_AS_NAMED` beside it, `_compiled.FAMILIAR` (the familiar forms) and `_compiled.ALTERNATE_SPELLINGS` (the alternate spellings) are the same hazard: each `Lexicon` reads them once into its own `_same_as`, `_same_as_named`, `_familiar` and `_alternate` at construction, the default's cached, so an edit to the module misses every lexicon already built — configure the object (`lexicon.add(word, kind=..., same_as=...)`). `REGEXES`, the other mutable mapping through 2.x, went with `config/regexes.py` in 3.0 (#1008). `tests/v2/test_contracts.py::test_every_vocabulary_constant_is_frozen` sweeps every module in `nameparser/config/` (`_compiled` and `_ko_surnames` hold its constants) and names those five dicts as explicit exemptions rather than letting its `isinstance` filter drop them. @@ -292,7 +292,7 @@ The compiled sets, read by `Lexicon` (mostly as the `_sets` field of the same na The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2.0 and then 3.0 deleted. These conventions apply to all of it. The design record (rationale, settled-decision logs, dated amendments) is docs/design/: `nameparser-2.0-rfc.md`, the rules, the decisions entries and mechanisms.md; this section is the enforceable subset. **A commit that establishes or amends one of these conventions must update this section in the same commit** — grep-driven staleness sweeps miss paraphrased prose (see Workflow above), so write-time maintenance is the mechanism, audits are the backstop. - **Module layout**: every module is underscore-private (`_types.py`, `_lexicon.py`, `_policy.py`, `_locale.py`, `_render.py`, `_reading_index.py`, `_pipeline/`, `_parser.py`, and `_match.py`, which holds name matching: `Matching`, the settings object `Parser.matching()` builds, and its result types, and `_suggest.py`, the group suggester: `Parser.suggest` tallies one vote per name from per-name signals and returns a `Suggestion`, decided under the thresholds in the decisions file group-suggestion). The public import surface is exactly `nameparser` and `nameparser.locales` (the vocabulary's compiled sets are private since 3.0, #1007, the Korean surname list since #1077 (2.8.2 warning of it, #1076), and `regexes` went with #1008; `tests/v2/test_layering.py` refuses a public module in `nameparser/config/`); `nameparser/__init__.py` holds re-exports and `__all__` only — no logic. -- **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; every locale pack module (`locales/*.py`) imports `_locale`/`_lexicon`/`_policy`/`_types` and its own private data modules in `locales/` only (`es.py` imports `_es_given_names.py`, `es_ar.py` `_es_ar_given_names.py`; `_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), a data module (a leading underscore) imports nothing internal, and the `locales/__init__` additionally lazy-imports its packs (PEP 562). No pack is keyed by hand: the test's `_locale_rules()` holds every file in `locales/` to that rule, a relative import read by the absolute name it resolves to, so a new pack is checked from its first commit. Extend the test's `ALLOWED` table when adding any other module; its completeness checks fail on a `_pipeline/` module it does not key and on a `locales/` module no rule reaches. +- **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; every locale pack module (`locales/*.py`) imports `_locale`/`_lexicon`/`_policy`/`_types` and its own private data modules, or its language pack's, in `locales/` only (`es.py` imports `_es_given_names.py`, `es_ar.py` `_es_ar_given_names.py`, and `pt_br.py` and `pt_pt.py` share `_pt_given_names.py`, #1453; `_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), a data module (a leading underscore) imports nothing internal, and the `locales/__init__` additionally lazy-imports its packs (PEP 562). No pack is keyed by hand: the test's `_locale_rules()` holds every file in `locales/` to that rule, a relative import read by the absolute name it resolves to, so a new pack is checked from its first commit. Extend the test's `ALLOWED` table when adding any other module; its completeness checks fail on a `_pipeline/` module it does not key and on a `locales/` module no rule reaches. - **Canonical field order** — the seven roles in `Role` enum declaration order, defined once and derived everywhere (properties, `as_dict`, reprs, `comparison_key`). Never restate the order literally. `Role` is a `StrEnum`: members compare as their field-name strings, and `tokens_for()` coerces strings via `_coerce_enum`. - **Method organization**, fixed section order in every class: fields + `__post_init__` validation → alternative constructors → dunders (construction/equality → protocol → operators) → properties → public methods by concern (access → editing → comparison → rendering delegates) → private helpers last, except a helper serving exactly one section may sit at that section's head. - **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). diff --git a/README.rst b/README.rst index 4561143ff..00e677c54 100644 --- a/README.rst +++ b/README.rst @@ -184,7 +184,7 @@ the patronymic in Russian. See `Locale packs >>> ivan.given, ivan.patronymic, ivan.family ('Иван', 'Петрович', 'Сидоров') >>> locales.available() # every pack that ships - ('ar', 'bn', 'cs', 'es', 'es_ar', 'ga', 'gd', 'he', 'hi', 'hr', 'ja', 'mn', 'my', 'ne', 'nl', 'pt', 'pt_br', 'ru', 'sk', 'sl', 'tr_az', 'vi', 'zh') + ('ar', 'bn', 'cs', 'es', 'es_ar', 'ga', 'gd', 'he', 'hi', 'hr', 'ja', 'mn', 'my', 'ne', 'nl', 'pt', 'pt_br', 'pt_pt', 'ru', 'sk', 'sl', 'tr_az', 'vi', 'zh') When a reading is wrong for your data ------------------------------------- diff --git a/docs/customize.rst b/docs/customize.rst index 444278721..842b062a9 100644 --- a/docs/customize.rst +++ b/docs/customize.rst @@ -1065,8 +1065,8 @@ taken: If you know your data's language, choose it rather than editing the words one at a time: a chosen language's connective is a connective even in a name written in one case, and the fork is no longer reported. -For Portuguese ``e``, use the ``pt`` pack (``locales.PT_BR`` reads it the -same way): +For Portuguese ``e``, use the ``pt`` pack (``locales.PT_BR`` and +``locales.PT_PT`` read it the same way): .. doctest:: diff --git a/docs/design/decisions/O6-two-family-names.md b/docs/design/decisions/O6-two-family-names.md index 302f6f7f1..4cc657e5e 100644 --- a/docs/design/decisions/O6-two-family-names.md +++ b/docs/design/decisions/O6-two-family-names.md @@ -3,8 +3,9 @@ ## Standing - Two family names are an opt-in `Policy` switch, `two_family_names`, off by default: the convention is Spain's and most of Latin America's but not Argentina's, and given-first it is the same string shape as a name with a middle name, so no default can read it — 2026-10-24 #754. -- `locales.ES` turns the switch on, carrying the Spanish given-name list beside it, one pack for Spain and Latin America alike, Argentina's own pack, `locales.ES_AR`, aside; `locales.PT` leaves it off until a Portuguese given-name list exists, decided in chat — 2026-10-30 #753, phase 3g. -- `locales.ES_AR` is `locales.ES` with a longer list, INE's tables cut at 5,000 words of at least half given-name use: it chooses `es-AR`, which selects es.toml, and reads es.toml's `[rules]`, so the switch stays on; a country pack names its language's table, no table inheriting another's — 2026-11-04 #1061 (Derek). +- `locales.ES` turns the switch on, carrying the Spanish given-name list beside it, one pack for Spain and Latin America alike, Argentina's own pack, `locales.ES_AR`, aside, decided in chat — 2026-10-30 #753, phase 3g. +- `locales.PT`, the pack chosen by language, leaves the switch off whatever list exists, being chosen for Angolan and Mozambican names too, which lose under it; `locales.PT_BR` and a Portugal pack, `locales.PT_PT`, turn it on, each country's own file (`pt-BR.toml`, `pt-PT.toml`, the second holding nothing but its table) writing the `[rules]` table `pt.toml` does not, and both carry one Portuguese given-name list — 2026-11-19 #1453. +- `locales.ES_AR` is `locales.ES` with a longer list, INE's tables cut at 5,000 words of at least half given-name use: it chooses `es-AR`, which selects es.toml, and reads es.toml's `[rules]`, so the switch stays on; it names its language's table, no table inheriting another's (a country writing a rule its language does not writes a table of its own, 2026-11-19 #1453) — 2026-11-04 #1061 (Derek). - `locales.CS` and `locales.SK` turn the switch on with no given-name list, a net gain in every real population measured (CLDR's fictional renderings lose), two given names the recorded cost; `locales.SL` and `locales.HR` leave it off, decided in chat — 2026-10-30 #753, phase 3f amended. - Both family names stay in `family` through 2.x; a second-surname field is the RFC's Phase 4 output model (docs/design/vocabulary-model-rfc.md, "The rules a pack can choose"), and a pack may later switch this rule on — 2026-10-24 #754; landed as the `surname2` view, `family` keeping both, 2026-10-29 #754, sub-phase 4d. - The family's words are counted as P1's fold counts them, a connective join and a hyphen counting as their words, so a family already holding two keeps what it has; the word taken must count as one, a hyphenated word counting as one there unless it writes given names (each part a listed given name or an initial), and be no initial written alone — 2026-10-24 #754; 2026-11-03 #959 (Derek). @@ -18,6 +19,7 @@ - The veto stays a clause of this rule though it reads a second signal, the taken word looked up in a list, and the rule is a split candidate — 2026-10-30 #959, decided. - Given-first, a particle run and the one word behind it whose `given` reading is written `after_particle` (rules/P10), standing beside a given name of one word, is not taken; under a family-first order it is, completing no given name there. Neither side of a join holding a name reading written `shared` (Sikh `kaur`, `singh`) is joined: each is no family name, and with the switch alone the name reads as with it off — 2026-11-03 #704, decided in chat. - The Spanish list, which `locales.ES` carries as its lexicon fragment since sub-phase 3g (a caller may pass a list of its own), is generated, not per-word vocabulary: INE's 2025 census tables, pooled over every name borne in Spain, cut at a measured rank (1,000 words, 90% given use) by `tools/es_given_names.py`; a change to it is a cutoff change — 2026-10-30 #959. +- The Portuguese list, `locales.PT_BR`'s and `locales.PT_PT`'s, is generated too, by `tools/pt_given_names.py`: ORCID's given and family boxes of researchers in Portugal and Brazil, pooled, past the first 3,000 records of each country, which are left for scoring; every word of at least 5 uses and at least 70% given use, each word read by hand, each ç word listed again with c; a change to it is a cutoff change — 2026-11-19 #1453. - A list per region, or another selection rule, for any Spanish-speaking country but Argentina is declined, each staying on `locales.ES`: in every group of at least 100 records measured, ES_AR's longer list beats ES's by at most 0.61 point on ORCID and no combination of the shipped switches beats `locales.ES` by more than 0.06 point, far below the country-pack measure's 2 points, and a list pooled over six countries came within half a point of per-country lists everywhere but Argentina and Peru — 2026-11-05 #1079 (Derek). - The shipped lists hold each word written with ñ again with n where that spelling passes the list's own share over every spelling it stands for, so a name from data without the letter matches; a word written with ñ matches no entry written with n, and neither the list's matching nor `_normalize` folds ñ — 2026-11-05 #1081 (Derek). @@ -126,7 +128,7 @@ PSC (`psc-individuals`, the fetch recorded on #849), a second population the list was not built from, by nationality, default → switch → switch and list, fixed and broken: Spanish 6,089 records 31.8% → 80.2% → 82.2% (150, 31), Mexican 402 25.9% → 80.1% → 82.1% (13, 5), Colombian 377 29.2% → 84.4% → 87.0% (15, 5), Venezuelan 237 40.5% → 75.9% → 80.6% (13, 2), Chilean 151 35.1% → 77.5% → 84.8% (12, 1), Peruvian 116 21.6% → 81.0% → 83.6% (5, 2), Argentine 320 81.9% → 45.6% → 81.9% (121, 5). Recompute: `uv run --with openpyxl --with xlrd python tools/es_given_names.py --top N` writes the list for a cutoff (`--write`) and prints its coverage. For ORCID, `local_agreement.read` per record of `local_corpora.load("orcid-researchers")` with `FIELDED["orcid-researchers"]`, records with both boxes, grouped by `country`, under `Parser()`, `Parser(policy=Policy(two_family_names=True))` and that policy with `lexicon=Lexicon.default() | Lexicon(given_names=...)` (`add(given_names=...)` before 3.0's 4i-b) holding the tool's first N words, each with `_title_words` of its own lexicon; family-first, the record's `name` replaced by `family + " " + given` and each policy given `name_order=FAMILY_FIRST`. For PSC, `local_agreement.score(rows, FIELDED["psc-individuals"], parser, jobs=1)` over the records whose `group_of` is the nationality, each cell a group's `agreed` over its `scored`. A record is fixed where it agrees only with the list, broken where it agrees only without it. The comparator is the switch alone on the same tree; `local_agreement.py orcid-researchers --base` and `psc-individuals --base` against master match the base, the default reading no list. - 2026-10-30 #959, decided — THE VETO STAYS A CLAUSE OF O6, THOUGH IT READS A SECOND SIGNAL. docs/design/AGENTS.md ("One rule per piece of evidence") says a clause reading a signal its rule did not already read is a new rule, and the veto reads one O6 did not: the word standing where the family would take one, looked up in the caller's given-name list (the #961 review). Kept in O6 anyway, decided 2026-10-30: the veto is one more member of the class the Except bullet "What is taken must be one name word a family name could be" already holds, beside the initial written alone and the mark with no letter in it. It only declines a take O6 would otherwise make, and reads nothing of its own: with the switch off it is never asked, and where it declines the name reads as with the switch off. A rule of its own would state no reading but O6's absence. The Signal line names the lookup as a second signal joined with ` + `, tagged `position` as P1's vocabulary signal is, by where the word stands, so O6 shows in the split-candidate grep; the next signal O6 gains is the point to split it. -- 2026-10-30 #753, phase 3g, decided in chat — (Its one pack for Argentina superseded in part by the 2026-11-04 #1061 entry: `locales.ES_AR` reads Argentine names, `locales.ES` unchanged.) `locales.ES` TURNS THE SWITCH ON; `locales.PT` DOES NOT. The `es` pack's `[rules]` table writes `two_family_names = true` (sub-phase 4f's schema), compiled into its policy patch, and the pack carries `nameparser/locales/_es_given_names.py`'s list as its lexicon fragment, so a caller choosing it reads `Gabriel García Márquez` with family `García Márquez` and `José Luis Pérez` with family `Pérez`. `two_given_names` stays opt-in in both packs (decisions/O7's phase 3g entry). The table answers two questions, each by its own comparison. Against the DEFAULT: should the pack turn the switch on at all, which is what a caller choosing the pack gets over not choosing it; every Spanish-speaking country gains on ORCID, Argentina least (82.5% → 89.3%), and PSC by nationality gains everywhere but Argentina, which ties. Against O6 ALONE: does the list help once the switch is on, the #959 entry's cutoff question, here re-measured on the pack as shipped, so the column holds the es choice's titles beside the list; against O6 with the list and no choice the pack differs on 9 ORCID records of these countries, all broken by a title the choice turns on (Cuba 7, `Lic.Alina Maren Ferrier`, `Lic Arisleidy Noriega Cisneros`; Venezuela 2, `Doctora Yenny Nereida Montilla Polo`, `PROFESORA CAROLINA GONZALEZ`), the box holding the title the filer typed in; it does in every country but Peru (178 fixed, 189 broken), the one the #959 review found net negative, a loss of 0.1 points that the pack's gain over the default there (16,197 fixed, 146 broken) dwarfs. So the Open line on Latin America stays a question about a better list, not about whether the pack should read two family names. The rows for the United States and Great Britain show the cost to data the pack is not meant for, which a caller choosing it accepts. +- 2026-10-30 #753, phase 3g, decided in chat — (Its one pack for Argentina superseded in part by the 2026-11-04 #1061 entry: `locales.ES_AR` reads Argentine names, `locales.ES` unchanged.) (Its `locales.PT` waiting for a list answered by the 2026-11-19 #1453 entry: `locales.PT` stays off whatever list exists, and `locales.PT_BR` and `locales.PT_PT` carry a list measured on ORCID.) `locales.ES` TURNS THE SWITCH ON; `locales.PT` DOES NOT. The `es` pack's `[rules]` table writes `two_family_names = true` (sub-phase 4f's schema), compiled into its policy patch, and the pack carries `nameparser/locales/_es_given_names.py`'s list as its lexicon fragment, so a caller choosing it reads `Gabriel García Márquez` with family `García Márquez` and `José Luis Pérez` with family `Pérez`. `two_given_names` stays opt-in in both packs (decisions/O7's phase 3g entry). The table answers two questions, each by its own comparison. Against the DEFAULT: should the pack turn the switch on at all, which is what a caller choosing the pack gets over not choosing it; every Spanish-speaking country gains on ORCID, Argentina least (82.5% → 89.3%), and PSC by nationality gains everywhere but Argentina, which ties. Against O6 ALONE: does the list help once the switch is on, the #959 entry's cutoff question, here re-measured on the pack as shipped, so the column holds the es choice's titles beside the list; against O6 with the list and no choice the pack differs on 9 ORCID records of these countries, all broken by a title the choice turns on (Cuba 7, `Lic.Alina Maren Ferrier`, `Lic Arisleidy Noriega Cisneros`; Venezuela 2, `Doctora Yenny Nereida Montilla Polo`, `PROFESORA CAROLINA GONZALEZ`), the box holding the title the filer typed in; it does in every country but Peru (178 fixed, 189 broken), the one the #959 review found net negative, a loss of 0.1 points that the pack's gain over the default there (16,197 fixed, 146 broken) dwarfs. So the Open line on Latin America stays a question about a better list, not about whether the pack should read two family names. The rows for the United States and Great Britain show the cost to data the pack is not meant for, which a caller choosing it accepts. | Source | Group | Records | Default | O6 alone | locales.ES | ES vs default, fixed / broken | ES (list and choice) vs O6 alone, fixed / broken | |---|---|---:|---:|---:|---:|---:|---:| @@ -171,7 +173,7 @@ - 2026-11-03 #959 (Derek) — A HYPHENATED WORD COUNTS AS ONE WHEN IT IS THE WORD TAKEN, UNLESS EVERY PART OF IT IS A LISTED GIVEN NAME OR AN INITIAL. SUPERSEDES, in part, the 2026-10-24 #754 entry's count of the word taken, in which a hyphen joined two words without making them one, so `Andrés Sánchez-Cid Torres` kept `Sánchez-Cid` a middle name (the #754 review's reading of `Ana María-José López`, middle 'María-José', which the first draft had read as family 'María-José López'). The issue found this shape behind 271 of the 466 Spanish records the given-name veto still read wrong. Measured 2026-11-03 on the cached `orcid-researchers` corpus, ES, MX, CO, PE, CL, VE and AR at most 20,000 records a country with both boxes (135,735 records), over the 10,794 distinct records holding a hyphen in either box, rendered given first and read right where both the family and the given names match the boxes (`local_agreement.fold`), under `parser_for(locales.ES)`, on 39839b91 against prototypes of three readings: a hyphen counting as one everywhere O6 counts (family and word taken) reads 10,038 right against 10,281, fixing 277 and breaking 520, most of them a family box of two surnames written with a hyphen (`Garcia-Gomez`), which then counts as one and takes a given name; a hyphen counting as one in the word taken alone reads 10,464, fixing 186 (ES 125, MX 24, CL 20, PE 6, CO 5, VE 5, AR 1) and breaking 3 (`Aristide Tanyi-Jong Akem`, `Hilda Ines-Romero Menacho`, `Benjamin Moraga-Arias .`); and the same with a veto on a hyphenated word every part of which is a listed given name, which moves none of these records. Decided: the word-taken count with the veto, the veto keeping the rule's own `Ana María-José López` where the Spanish list is loaded (middle 'María-José'), while without a list the switch takes it (family 'María-José López'), its usual cost (rules/O6's Accepted). Found building it and in its review, and folded into the veto, which reads each part: a part that is an initial counts as a listed given name does, so hyphenated initials (`Ana M.-J. López`) stay as an initial written alone stays, and `M.-José` stays under the list, which moves no ORCID record. A hyphenated bound given-name pair (`Ana Abdul-Rahman López`, middle 'Abdul-Rahman' in 2.8.0) is taken like any hyphenated word, family 'Abdul-Rahman López', where the pair written as two words (P5) stays: a veto on a hyphenated word whose first part is a bound given name was built and backed out the same day, since in this population it cost 2 records whose hyphenated word is a surname (`Paola Valentina Abdul-Hadi Pru`, `Giorgia Anette Abd-El-Kader Espinoza`) and kept none, the hyphen being how those surnames are written; rules/O6's Accepted records the cost. A hyphen in the family still counts its words, so `Javier Olmedo Pérez-Montaut` keeps `Olmedo` a middle name: reading `Pérez-Montaut` as one surname is the 520 above. The built change reads the same 10,464 and moves the same 186 and 3, and with the switch alone (`Policy(two_family_names=True)`, no list) 10,292 to 10,475, the same records. Recompute: for each record of `local_agreement.records(local_corpora.load("orcid-researchers"))` in those countries, both boxes non-empty, at most 20,000 a country, keep those with a hyphen (`_post_rules._HYPHENS`) in either box, distinct by given box, family box and country (two records are duplicates), parse `f"{given} {family}"` with each tree's parser, `nameparser.__file__` asserted, and compare. - 2026-11-03 #959 — (Superseded for a word written `after_particle` by the 2026-11-03 #704 entry: `María del Carmen de la Vega` reads given 'María del Carmen' with both switches on.) BOTH SWITCHES OVER A GIVEN NAME A PARTICLE COMPLETES GET AN EXAMPLE. The 2026-10-30 entry's Open named the shape no rule example showed: `María del Carmen de la Vega` reads family 'del Carmen de la Vega' with both switches on, O6 taking the chain before O7 can complete the given name with it, and given 'María del Carmen' under O7 alone. rules/O7's precedence bullet against two-family-name handling now says so and carries both rows; no behavior moves. - 2026-11-03 #704, decided in chat — A GIVEN NAME A PARTICLE COMPLETES, AND A NAME A COMMUNITY GIVES EVERY MEMBER, ARE NO FAMILY NAME. SUPERSEDES, for a marked word, the 2026-11-03 #959 entry's reading of `María del Carmen de la Vega` with both switches on: this rule now leaves `del Carmen` where it stands, so the name reads middle `del Carmen` with this switch alone and given `María del Carmen` with both (decisions/O7's entry of this date holds the property, the word list and the measurements). The second clause is the Kaur and Singh decline that entry records: `Harpreet Kaur Dhillon` read family `Kaur Dhillon` under this switch and reads middle `Kaur`, family `Dhillon`, as by default; a shared word as the family declines too, so `Harpreet Simran Kaur` keeps family `Kaur`. Like the given-name list (the 2026-10-30 #959 entry), each reads the vocabulary, the signal this rule already reads beside its count, so they stay clauses of this rule; the shared-name clause reads it at a second site, the family's own words as well as the word taken, recorded on the rule's Signal line. The given-name clause reads only the shape rules/O7 takes, given-first beside a given name of one word: the review of #1057 found the first draft declining under a family-first order (`García del Valle María` lost family `García del Valle`) and behind a middle (`Juan Antonio del Valle de la Vega` under `locales.ES` lost family `del Valle de la Vega`), where no given name is completed. -- 2026-11-04 #1061 (Derek) — `locales.ES_AR`, ARGENTINE SPANISH, IS `locales.ES` WITH A 5,000-WORD GIVEN-NAME LIST CUT AT HALF GIVEN-NAME USE. The 2026-10-27 entry's ORCID table showed the switch costing Argentina (80.3% → 59.7%, before the list), but that was the switch without the list: with it (phase 3g) `locales.ES` raises ORCID's Argentine researchers and loses only on PatentsView's Argentine inventors, who mostly write two given names and one surname. There the switch takes the second given name wherever Spain's list lacks it, and INE's 90% bar leaves out given names Spain also bears as surnames in a seventh to a quarter of their uses (`Nicolás` 76% given, `Matías` 76%, `Sebastián` 81%, `Andrés` 77%, `Ramón` 85%, INE's tables as `tools/es_given_names.py` tallies them); the list is matched accent-folded, so spelling is not the cause (adding every entry's unaccented form moved no record). Turning the switch off for Argentina reads exactly as the default does, losing 6.7 points on ORCID, so the country pack keeps it on and lengthens the list instead: the same tables at a share of 0.5, 5,000 words, which holds every word of ES's, so the two packs stacked read as ES_AR. `Martín` and `Esteban` stay out (Spain bears each mostly as a surname even at 0.5), so the switch still takes them. All boxes agreeing, by list (the knobs, `--share` then `--top`): +- 2026-11-04 #1061 (Derek) — (Its shape bullet's premise that no country measured turns a rule differently from its language superseded by the 2026-11-19 #1453 entry: Brazil and Portugal turn O6 on where `pt.toml` does not, each in a file of its own; the decline of `[rules]` inheriting along a tag's ancestors stands. Its "`locales.PT` keeps waiting for a list" answered by the same entry: it stays off. Its country-pack measure is missed by `locales.PT_BR` on PatentsView's Brazilian inventors, knowingly, as that entry records and decides, and its list clause, "a list cut from a published source by `tools/es_given_names.py`", was met there by a list the project measured on ORCID with `tools/pt_given_names.py`.) `locales.ES_AR`, ARGENTINE SPANISH, IS `locales.ES` WITH A 5,000-WORD GIVEN-NAME LIST CUT AT HALF GIVEN-NAME USE. The 2026-10-27 entry's ORCID table showed the switch costing Argentina (80.3% → 59.7%, before the list), but that was the switch without the list: with it (phase 3g) `locales.ES` raises ORCID's Argentine researchers and loses only on PatentsView's Argentine inventors, who mostly write two given names and one surname. There the switch takes the second given name wherever Spain's list lacks it, and INE's 90% bar leaves out given names Spain also bears as surnames in a seventh to a quarter of their uses (`Nicolás` 76% given, `Matías` 76%, `Sebastián` 81%, `Andrés` 77%, `Ramón` 85%, INE's tables as `tools/es_given_names.py` tallies them); the list is matched accent-folded, so spelling is not the cause (adding every entry's unaccented form moved no record). Turning the switch off for Argentina reads exactly as the default does, losing 6.7 points on ORCID, so the country pack keeps it on and lengthens the list instead: the same tables at a share of 0.5, 5,000 words, which holds every word of ES's, so the two packs stacked read as ES_AR. `Martín` and `Esteban` stay out (Spain bears each mostly as a surname even at 0.5), so the switch still takes them. All boxes agreeing, by list (the knobs, `--share` then `--top`): | List | ORCID AR, 19,364 | PatentsView AR, 3,343 | PSC Argentine, 320 | |---|---:|---:|---:| @@ -200,3 +202,59 @@ - Declined: a two-way fold in the list's matching. A surname written with ñ then matches an entry written with n whatever the share, and the tool's tallies of INE's tables show such entries mostly borne as surnames once the ñ spelling is summed in: in both lists `ona` (Oña, 3,569 surname uses) at 69.7% given and `rene` (Reñe, 1,192) at 82.0%, under ES's 90% though over ES_AR's half, and in ES_AR's `marino` (Mariño, 14,726) at 18.3%, `nino` (Niño, 10,402) at 12.1% and `nuno` (Nuño, 7,041) at 23.6%. Over the 13 local corpora it moves 28 surnames written with ñ out of the family under ES and 149 under ES_AR, with 20 Martino under ES_AR; in ORCID, 135 of those words stand in the filer's family box and 27 in a given box. It fixes what the shipped change fixes, and nothing more. - Excluded: `martino`, the n spelling of `martiño` (ES_AR): Martino is mostly a surname, 155 given uses against 2,528 as the tool tallies them, so the merged spelling, 897 given against 2,842 surname, is 24.0% given against ES_AR's 50% share (martiño alone 70.3%, 742 against 314). The share test leaves it out, and without it `Luis Martino Gil` would read family 'Gil' (6 tse-donors names, 20 over the 13 corpora). Recompute: `uv run --with openpyxl --with xlrd python tools/es_given_names.py` prints ES's candidate n spellings (`n` rows, each with its summed given and surname uses, its share and whether it is kept), and `--list es-AR` ES_AR's, martino's refusal among them on standard error; `--words` prints any word's tallied uses, so `--words Oña Ona Reñe Rene Mariño Marino Niño Nino Nuño Nuno Martino Martiño Iñigo Inigo` gives every other count quoted here. For the moves, run `config_diff.py diff default plain:ES plain:ES_AR --local SOURCE --match '(?i)ñ|n\u0303|\b(begona|benat|inaki|zurine|inigo|garbine|enaut|argine|eguzkine|ekine|alona|marina|martino|senor|senora|senores|senorita|senoritas|dona)\b' --readings FILE` in this tree and in the parent commit for each local corpus, and compare the two files line by line: the comparator is the parent commit. `config_diff.py score default plain:ES plain:ES_AR` with `--group` ES, MX, AR, CO, PE and CL in each tree gives the score. +- 2026-11-19 #1453 — `locales.PT_BR` AND A PORTUGAL PACK, `locales.PT_PT`, TURN THE SWITCH ON WITH A PORTUGUESE GIVEN-NAME LIST; `locales.PT` DOES NOT. Decided 2026-11-19 on the issue's measurements, the four questions in order: the pack chosen by language stays off, because a caller choosing it for Portuguese names from any country gets Angolan and Mozambican names too, which lose 10 to 35 points under the switch whatever list guards it; Brazil and Portugal each get the switch in a pack of their own; the list is Portuguese, measured on ORCID's boxes (CC0) rather than the Spanish one, which scored alike but lacks names Portuguese writes (`matheus`, `gonçalo`, `vitória`); and a family of three or more surnames is left for a question of its own, counted below. This is the reverse of Spanish, where the language pack carries the switch. + - **The shape.** `pt-BR.toml` gains a `[rules]` table, `two_family_names = true`, and a new `pt-PT.toml` holds that table and no word; `PACK_RULES` lists both; `pt.toml` holds none, so `rules_patch("pt")` raises and no table rides along a tag's ancestors (the 2026-11-04 entry's decline stands). A file holding only a table selects nothing of its own under a plain choice: `pt-PT` selects `pt.toml`, as `es-AR` selects `es.toml`, and a strict choice keeps the file, which holds nothing; `config_diff.py`'s `gap_specs` reads a plain choice of such a tag as the pack, not the default. The pack is `PT_PT`, code `pt_pt`, the existing convention for a country pack (`ES_AR`, `PT_BR`: the BCP 47 tag with an underscore, upper-cased for the attribute), so `--locale pt-PT` names it, where it named `pt` with a subtag before. Both packs import `nameparser/locales/_pt_given_names.py`, one list shared by a language's country packs, which tests/v2/test_layering.py's data-module rule now admits (a data module belongs to the pack whose stem opens its name and to that pack's country packs). Each declares rules/O6's `DEVIATES`, as `locales.ES` does. + - **The list.** `tools/pt_given_names.py` reads the `orcid-researchers` local corpus, the records of Portugal and Brazil with both boxes filled past the first 3,000 of each country in the corpus's order, which `config_diff.py score --cap 3000` reads, so no record the list is built from is scored. A word's uses are the given boxes and family boxes holding it, a family word after a particle not counted (a unit O6 takes whole), folded by `given_name_key`. Shipped: 719 words of at least 5 uses at least 70% of them given, ranked by given uses, and two c spellings (`goncalo`, `constanca`), 721 entries. Every word was read by hand; none was taken out (`REMOVED` is empty). The words read most closely, kept as given names Portuguese writes: those borne often as surnames too (`augusto`, `henrique`, `francisco`, `jorge`, `aparecida`, `tomas`, `magno`), the second halves of compound given names that stand alone (`socorro`, `ceu`, `nazare`, `goreti`, `bosco`, `belem`), and given names Brazil writes from other languages (`wagner`, `wilson`, `jefferson`, `yan`, `sayuri`, `euler`). The vocabulary filter the Spanish tool applies took out `dr`. + - **The cut.** Scored with `config_diff.py score --cap 3000`, every box agreeing, the list under `two_family_names` and a `pt-PT` choice, the shipped list in bold; ORCID's Portugal and Brazil groups, and PatentsView's (US patents' inventors, which the list is not built from): + + | List | Words | ORCID PT | ORCID BR | PatentsView PT | PatentsView BR | + |---|---:|---:|---:|---:|---:| + | none (the default) | | 72.12% | 50.32% | 57.47% | 75.17% | + | the switch alone | | 83.03% | 74.21% | 62.60% | 51.87% | + | pooled, 10 uses × 0.7 | 435 | 89.57% | 79.58% | 65.43% | 60.73% | + | pooled, 5 × 0.5 | 747 | 89.70% | 79.96% | 65.70% | 61.73% | + | **pooled, 5 × 0.7** | **721** | **89.67%** | **79.82%** | **65.73%** | **61.37%** | + | pooled, 5 × 0.8 | 700 | 89.67% | 79.30% | 65.70% | 60.73% | + | pooled, 5 × 0.9 | 610 | 89.09% | 78.63% | 65.10% | 58.77% | + | pooled, 3 × 0.5 | 1,202 | 89.77% | 80.28% | 65.80% | 62.03% | + | pooled, 3 × 0.7 | 1,115 | 89.77% | 80.25% | 65.87% | 61.57% | + | Portugal's records alone, 5 × 0.7 | 309 | 89.53% | 78.53% | 65.43% | 59.47% | + | Brazil's records alone, 5 × 0.7 | 549 | 88.57% | 79.89% | 65.23% | 61.07% | + + One pooled list serves both: Portugal's own list reads fewer Portuguese records than the pooled one and Brazil's own gains 0.07 points in Brazil (two records) while losing 1.1 in Portugal. A floor of 3 or a share of 0.5 gains at most two thirds of a point (PatentsView BR at 3 × 0.5) and under half a point elsewhere, and 3 × 0.5 adds 481 words to read by hand, 454 of them of 3 or 4 uses, so 5 × 0.7 was chosen for most of the gain at the size a hand reading checks, and kept when the cut was weighed again on 2026-11-19. + - **What the packs change, per country.** Records agreeing in every box, the default (and `locales.PT`, which reads ORCID's composed names as the default does but for one Angolan and one Brazilian record) against `locales.PT_BR` and `locales.PT_PT`, which read these records alike, with the records fixed and broken against the default; ORCID's groups by where the holder works or lives, at most 3,000 records a country, PatentsView's likewise, the UK company register's (PSC) by nationality: + + | Group | Records | Default | `PT_BR`, `PT_PT` | Fixed / broken | + |---|---:|---:|---:|---:| + | ORCID Portugal | 2,923 | 72.1% | 89.7% | 629 / 116 | + | ORCID Brazil | 2,850 | 50.3% | 79.8% | 1,017 / 176 | + | ORCID Cape Verde | 563 | 61.5% | 80.5% | 147 / 40 | + | ORCID São Tomé and Príncipe | 121 | 50.4% | 71.1% | 32 / 7 | + | ORCID Guinea-Bissau | 220 | 66.8% | 72.3% | 46 / 34 | + | ORCID Timor-Leste | 495 | 64.0% | 67.1% | 88 / 73 | + | ORCID Angola | 2,861 | 76.4% | 65.3% | 386 / 706 | + | ORCID Mozambique | 2,853 | 85.6% | 67.2% | 166 / 689 | + | PatentsView Portugal | 3,000 | 57.5% | 65.7% | 731 / 483 | + | PatentsView Brazil | 3,000 | 75.2% | 61.4% | 393 / 807 | + | PSC Portuguese | 2,996 | 59.2% | 62.8% | 732 / 626 | + | PSC Brazilian | 1,920 | 53.7% | 62.9% | 588 / 412 | + | PSC Angolan | 98 | 85.7% | 58.2% | 1 / 28 | + + PatentsView whole, the same configurations: Brazil, 15,029 records, 75.7% under the default and `locales.PT`, 60.2% under `PT_BR` and `PT_PT`, 1,978 fixed and 4,317 broken; Portugal, 3,576 records, 57.6% and 66.1%, 869 fixed and 564 broken. Of Brazil's 4,317 broken records every one holds a single surname in the family box, 122 of them with an agnomen or `Jr.` beside it (`Santos, Jr.`, `Da Silva Neto`); in the other 4,195 the word the switch takes from the first-name box is mostly a family word in the list's build in 2,696 (`Eder Ferreira` / `Rangel`), a word no record of the build holds in 1,274 (a Japanese or Italian given name or a rare surname, `Jurandir Itizo` / `Yanagihara`), a given name under the cut in 217, an initial written joined in 7, and something else in 1 (an encoding artifact in the source, family box `da Encarna.cedilla.ao`). Portugal's 564 are the same shape: 458, 84 and 22. Where the parse's family holds more name words than the family box, the word classed is the first word of the parse's family that is no particle (nor `e`), folded by `given_name_key`: an initial where it is one letter or holds a full stop, a word no record holds where `tally` counts it nowhere, mostly a family word where its family uses are at least its given uses, a given name under the cut otherwise; with family uses greater than given uses in place of at least, 42 of Brazil's broken records move from the family class to the given class. + Every record of the six smaller countries is outside the list's build; read at a cap of 20,000 they give the same figures but Angola's (5,037 records, 76.2% → 65.4%) and Mozambique's (4,948, 85.4% → 67.2%). So Cape Verdean and São Toméan lists gain under `locales.PT_PT`, Guinea-Bissau's and Timor-Leste's a little, and Angolan and Mozambican ones lose. At the cap of 3,000, PatentsView's Brazilian inventors lose 13.8 points (15.6 over the whole corpus, above); the 2026-11-04 entry's switch alone, with no list, lost 24.5 (75.73% → 51.22%). So `locales.PT_BR` misses that entry's country-pack measure (at least 2 points over the language pack in every fielded source holding 300 of the country's records): decided 2026-11-19 that it ships with the switch on all the same, knowingly missing that measure there: the loss is a filing convention, one surname in the family box, which no list can tell from a name written whole, and the two populations whose names were split by the person or by their own filer, ORCID's researchers and the UK register's Brazilian nationals, gain; the user docs say to keep `locales.PT` for data filed with a single surname; of the 807 records broken, 487 hold in the first-name box a word the list's build holds in the family box at least as often as in the given box (`Eder Ferreira` / `Rangel`, read family `Ferreira Rangel`), a filer putting every name but the last in the first-name box, which no given-name list can tell apart; 253 hold a word the build's boxes never hold, mostly a Japanese or Italian given name (`Jurandir Itizo` / `Yanagihara`), 44 a given name under the cut, and 23 an agnomen or `Jr.` (19), an initial written joined (3) or the encoding artifact (1), classed as the whole-corpus records are. + - **What is left wrong.** Under `locales.PT_BR` (and `PT_PT`, which reads these records alike), by shape, each a share of the group's records and how many of them the default read right; the taken word's class read from the list's own tallies: + + | Shape | ORCID PT, 2,923 | ORCID BR, 2,850 | PatentsView PT, 3,000 | PatentsView BR, 3,000 | + |---|---:|---:|---:|---:| + | a family of three or more name words read as two | 117 (4.0%), 0 | 268 (9.4%), 0 | 378 (12.6%), 0 | 78 (2.6%), 0 | + | taken: a word mostly a family word in the build's boxes, a surname filed among the given names | 91, 73 | 174, 115 | 516, 390 | 654, 487 | + | taken: a word the build's boxes never hold | 28, 26 | 36, 31 | 78, 73 | 266, 253 | + | taken: a word mostly a given word but under the cut, a given name the list misses | 15, 15 | 26, 23 | 26, 20 | 53, 44 | + | not taken: the word before the family is listed, a listed given name borne as a surname (`Fábio` / `Francisco da Silva`) | 15, 0 | 29, 0 | 11, 0 | 18, 0 | + | a family box of two read as one otherwise | 31, 0 | 9, 0 | 13, 0 | 2, 0 | + | other (an initial written joined, a suffix the box holds, a particle left in the given box) | 5, 2 | 33, 7 | 6, 0 | 88, 23 | + + Families of three or more surnames are the largest gap in both of ORCID's groups and in PatentsView's Portuguese one, and the switch never broke one: it takes one word, so `Leonardo Mirandela Gomes Paz` keeps `Mirandela` a middle name (tests/v2/cases.py's `three_family_names_read_as_two_under_pt_br`). They are #1482. In Angola and Mozambique most of the records broken take a word no record the list is built from holds, mostly a given name written there (406 and 293 of the broken), or a surname filed among the given names (253 and 274). + - **On names as written.** Over the 848,351 names of `tse-donors` (Brazilian candidates' donors as filed), `locales.PT_BR` against the pack as it stood (a `pt-BR` choice, no list, no patch) moves 500,485, every one into the family: 418,432 take a word the list's build holds mostly as a family word (`alves`, `pereira`, `silva`, `ferreira`, `rodrigues`, `santos`), 66,222 a word the build's boxes never hold (`donizeti`, `assuncao`, `trajano`), 15,249 a word it holds mostly as a given word but under the cut (`cezar`, `tadeu`, `bernardo`, `raimundo`, `mauricio`, `donizete`, `mateus`; ORCID's holders write `mateus` and `bernardo` as surnames in about a third of their uses), and 491 an initial or a connective written in one case (`e`). Over the 7,644 committed corpus names it moves 1,543, nearly all names of three words or more outside Portuguese, the switch's declared cost (rules/O6's Accepted). CLDR's `pt` file, which the locale view reads with `locales.PT_BR`: its native given-first renderings read as before; two foreign ones (`Zäzilia Hamish Stöber`, given first and surname first) newly disagree, and three that disagreed already now disagree in the family: in the two surname-first ones (the native `da Silva Sr. José Pedro Eduardo Jr., MP` and a foreign one) a title written after the family (`da Silva Sr.`) is taken as the second surname, as `locales.ES` under `FAMILY_FIRST` reads it already, and in the foreign given-first one (`Prof. Dr. Mary Lou Cesare Martín von Brühl …`) the given name `Martín` is taken as the first surname, as in `Zäzilia Hamish Stöber` (`cldr_agreement_locales.json`, re-recorded). The default parse and `locales.PT` move nothing: `snapshot.jsonl` gains one rule example's text, rules/S11's `JOSE CARLOS F`, and changes no reading. + - **Not decided here:** a census source for Portugal's or Brazil's given names, which may replace the list; a rule for a family of three or more surnames (#1482); the words under the cut that Brazilian data writes as given names (`mateus`, `bernardo`, `tadeu`). + Measured 2026-11-19 on master at 6560abde and the branch, Python 3.11, ORCID's extract of 2026-10-27, PatentsView's and PSC's caches as fetched, tse-donors as fetched. Recompute: `uv run python tools/pt_given_names.py --min-uses M --share S [--countries PT|BR]` prints a list (`awk '$1 ~ /^[0-9]+$/ || $1 == "c" {print $2}'` keeps the words); score it as `expr:parser_for(Locale(code="x", lexicon=Lexicon(given_names=open("LIST").read().split()), policy=locales.PT_PT.policy, languages=frozenset({"pt-PT"})))` beside `default` with `config_diff.py score --cap 3000 --group PT --group BR`, the comparator `default`, never the list measured; the per-country table is `config_diff.py score default plain:PT plain:PT_BR plain:PT_PT --cap 3000 --min 50` with `--group` each of PT, BR, CV, ST, GW, TL, AO, MZ, and `Portuguese`, `Brazilian`, `Angolan` for PSC, fixed and broken read from each configuration's `score_rows` counts against `default`; the shapes classify each record `local_agreement.read` marks wrong under `locales.PT_BR` by the family box's name words (particles and `e` not counted) against the parse's and by the first word the parse took, looked up in `tools/pt_given_names.py`'s `tally`; the tse-donors and committed moves are `config_diff.py diff 'expr:parser_for(Locale(code="old", lexicon=Lexicon.empty(), languages=frozenset({"pt-BR"})))' plain:PT_BR --local tse-donors --readings FILE` (and `--committed`), the expression being the pack as it shipped in 3.1. diff --git a/docs/design/decisions/S11-suffix-word-that-is-also-a-name.md b/docs/design/decisions/S11-suffix-word-that-is-also-a-name.md index 8d151e7fc..c15d5cbcb 100644 --- a/docs/design/decisions/S11-suffix-word-that-is-also-a-name.md +++ b/docs/design/decisions/S11-suffix-word-that-is-also-a-name.md @@ -10,7 +10,7 @@ - The floor holds before a generation word's case: a lower-case `fils` in a mixed-case name is the generation only where the name keeps a family word, so `Dumas fils` and `Pedro Jnr fils` read family 'fils' — 2026-10-25 (Derek), #890, THE FLOOR (its example re-spelled 2026-11-03 #1039, `Pedro Junior fils` reading family 'Junior', suffix 'fils' since Junior is a name too). -- The abbreviations Brazilian filings write for the agnomens are agnomen spellings `same_as` their word, gated as it is: `fh`, `fo`, `filh` (filho), `net`, `nt` (neto), `sob`, `sobr` (sobrinho), each with a `family` reading, counted or declared, so that a name of two words keeps it (`Ana Fo` → family 'Fo'); `fil` is refused on the word, `sb` is read only under a Brazilian Portuguese choice, and the single letters `F` and `N` are left to read as the name word they are written as, an initial or, ending the name, the family (`JOSE CARLOS SILVA F` → family 'F'), under that choice too — 2026-10-27 #843; 2026-10-30 #753, phase 3h. +- The abbreviations Brazilian filings write for the agnomens are agnomen spellings `same_as` their word, gated as it is: `fh`, `fo`, `filh` (filho), `net`, `nt` (neto), `sob`, `sobr` (sobrinho), each with a `family` reading, counted or declared, so that a name of two words keeps it (`Ana Fo` → family 'Fo'); `fil` is refused on the word, `sb` is read only under a Brazilian Portuguese choice, and the single letters `F` and `N` are left to read as the name word they are written as, an initial or, ending the name, the family (`JOSE CARLOS SILVA F` → family 'F'), under that choice too, where `locales.PT_BR` reads two family names and so takes the word before it into the family (family 'SILVA F') — 2026-10-27 #843; 2026-10-30 #753, phase 3h; 2026-11-19 #1453. - King's Counsel is a credential listed as a word (`kc`, `acronym = false`), gated by its name readings as a generation word is, so the Nepali surname KC keeps the family where the name has no word to spare (`Ram KC`) or writes it in Title case (`Gita Bahadur Kc`), and its dotted spelling stays #864's paired initials (`Gita Bahadur K.C.`); the costs are accepted: `Gita Bahadur KC` reads suffix 'KC', `Lord Doe KC` family 'KC', and a family comma's given part ending in initials written KC reads them as the credential (`DOE, JANE KC`); the Privy Counsellor's `pc` and the Deputy Lieutenant's `dl` are credentials written as words in the same shape, initials being written that way too, so `Jane Doe, DL` reads the suffix and `Ravi PC` and `Anna DL` keep the family, the dotted `P.C.` and `D.L.` reading as master read them — 2026-10-30 #965. @@ -38,3 +38,4 @@ Open: none in this file. ACCEPTED BY THIS CHANGE, NOT YET PUT TO A DECISION. A name of two words ending in Junior keeps it as the family name where the writer meant a given name and the generation with no surname written (`Fabio Junior`, `ADELSON JUNIOR`). In front of another suffix word that is also a name Junior is a name word, as Neto is in `Pedro Neto Filho`, so the word behind it is the suffix and Junior the family name: `Pedro Junior Filho` reads family 'Junior', suffix 'Filho', `Pedro Junior fils` family 'Junior', suffix 'fils', `Pedro Junior Filho, MD` suffix 'Filho, MD', `Pedro Junior do Filho` suffix 'do Filho', and `Pedro Junior Ma Filho` middle 'Junior', family 'Ma', where 1.4.0 through 2.8.1 read middle 'Junior' (middle 'Junior Ma' for `Pedro Junior Ma Filho`) with the agnomen or `fils` the family name. The 2026-10-25 (Derek), #890 entry's examples and THE FLOOR's were written with Junior; they are re-spelled with `Jnr`, a generation word with no name reading, which reads as Junior did (`Pedro Jnr Filho` → family 'Filho'), and the case rows and S7's and S11's examples likewise. A Brazilian surname written with its generation before a comma joins the family (`BRITO JUNIOR, RAIMUNDO C` → family 'BRITO JUNIOR'). A comma credential the vocabulary does not list behind a name of two or more words ending in Junior takes it into the family name, where the base already reversed the name (`JOSE ROBERTO DA SILVA JUNIOR, DOCTORATE` → family '… JUNIOR', given 'DOCTORATE'). A bracketed Junior is the nickname, as `(Neto)` is (rules/S13; `John Smith (Junior)` → nickname 'Junior', 5 psc-individuals names). And a period-marked Junior opening the given part after a family comma is a title by rules/H2's shape, as `Smith, Neto.` and `Smith, Fils.` are, where 2.2.0 through 2.8.1 read the suffix (`Smith, Junior.` → title 'Junior.', as 2.0.0 and 2.1.0 read it, 1.4.0 the title with no family name); no corpus name writes it so. MEASURED (2026-11-03, `tools/differential/measure.py --base` against master 39839b91, on the change before review; the review re-ran it on the committed tree through ctgov-officials, identically). Committed snapshot: the rules' and case table's Junior names only (9 entries). The CLDR, GND and Wikidata records do not move. Local snapshots, entries that differ, nearly all a new `suffix-or-name` report alone: tse-donors 14,839 (14,763 a report alone; 38 two-word names gaining family 'JUNIOR', 8 trailing words a registry appended moving Junior into the family, 3 `X JUNIOR FILHO`/`NETO`), jrc-names 391 (177 two-word names, `Fabio Junior` → family 'Junior'), orcid-researchers 505 (441 a report alone), patentsview-inventors 212 (211), psc-individuals 97 (86; `Mr Oliver Junior` → given 'Oliver', family 'Junior', 4, and the bracketed Junior, 5), ctgov-officials 87 (77; 7 `… Junior, Médico`-shaped comma names, above; 3 where `Junior` names a post opening the part after a comma, `Rune Broni Strandby, Junior researcher` → given 'Junior', and `Pauline PL LUDWIG, Doctor junior` → given 'junior'), fec-individuals 61 (29 `SURNAME, JUNIOR` names and 13 more with Junior opening the given part, 42 gaining the given name, the thirtieth, `ABREU RODRIGUEZ, JUNIOR`, among the reports alone; 9 `BRITO JUNIOR, RAIMUNDO`; 10 a report alone); cz-candidates, dof-signatures, govuk-people, nepal-candidates, tw-donors and ukec-individuals none. Agreement with the filed boxes: orcid-researchers 9 records progress, 4 regress, 3 change; psc-individuals 5 progress, 1 regresses, 5 change; patentsview-inventors and cz-candidates no move; jrc-names one person more read alike, tse-donors one pair apart. Pinned by the case rows `junior_after_a_family_comma_is_the_given_name`, `junior_alone_after_a_family_comma_is_the_given_name`, `junior_in_title_case_with_a_word_to_spare_is_the_suffix`, `junior_with_no_word_to_spare_is_the_family_name`, `junior_ending_the_given_part_after_a_family_comma`, `a_junior_in_front_of_an_agnomen_is_a_name_word` and `a_dotted_junior_opening_the_given_part_is_a_title`, `tests/v2/test_lexicon.py`'s `test_a_generation_word_that_is_a_name_leans_by_case_only_when_told`, and three build-check mutations. A 2.x `Lexicon` holding a word in `suffix_words_ambiguous` that is not an agnomen translates to a generation reading written `title_case_is_name`, the lean 2.x gave every such word, and the refusal naming the 3.0 call says so. Recompute: the command above against a checkout of 39839b91, and the three listings as `config_diff.py diff` expressions over `--local all --match '(?i)\bj[uú]nior\b'`. - 2026-11-16 #1230 — THE DOTTED-SHAPE EXAMPLES OF THE 2026-10-25 #752 LINE NO LONGER READ AS WRITTEN. The line's decision stands (a suffix word that is also a name makes no chunk claim inside a word with interior periods), but rules/T8 (decisions/T8, #1230, #1235) now divides an initial glued to the word at its full stop before any comma, before it is read, so `Pedro M.Filho` reads family 'M.', suffix 'Filho' where the line said family 'M.Filho', and `Pedro Alves M.Filho` middle 'Alves', family 'M.', suffix 'Filho' where it said suffix 'M.Filho'. After a comma, and for a word its own stop closes, the dotted-shape reading still acts (`Smith, Pedro M.Filho` → suffix 'M.Filho', `Silva, M.Filho` → given 'M.Filho', `Pedro Alves M.Filho.` → suffix 'M.Filho.'). The Standing line carries the readings now; found by the 3.1 release sweep. +- 2026-11-19 #1453 — `locales.PT_BR` READS TWO FAMILY NAMES, SO A LETTER ENDING THE NAME TAKES THE WORD BEFORE IT. Nothing this file decided moves: `F` and `N` stay out under the pack and read as the name word they are written as. But the pack turns on rules/O6 (decisions/O6, 2026-11-19), which takes the name word before the family, so `JOSE CARLOS SILVA F` reads family 'SILVA F' where it read 'F', and `Pedro Alves N.` family 'Alves N.'; behind a listed given name the letter is the family alone, as before (`JOSE CARLOS F` → family 'F'; the rule's examples hold both since). The agnomen rows the pack reads (`JOSE CARLOS SILVA SB` → suffix 'SB') do not move: the agnomen is peeled before O6 counts the family. diff --git a/docs/design/decisions/vocabulary-model.md b/docs/design/decisions/vocabulary-model.md index 6a6c0ab88..44bc7538a 100644 --- a/docs/design/decisions/vocabulary-model.md +++ b/docs/design/decisions/vocabulary-model.md @@ -8,7 +8,7 @@ The vocabulary was a set of base sets plus marker subsets (`particles` and `part - Each word is described by its readings (word → reading → properties), each kind belonging to one category that decides the compiled field it feeds; detailed kinds are recorded even where the kinds of a category behave alike, generation and credential being separate kinds of the suffix category (its kinds are the entries `CATEGORY` in `nameparser/_reading_index.py` maps to `suffix`) — 2026-10-15/16; 2026-10-18 #737. - A language file holds the words the parser might meet in names written in that language, immigrant particles included, not the words of its etymology, and a word sits in the file of every language whose names it occurs in, a Latin transliteration in its source language's file; `mul.toml` holds the words shared on purpose instead (the generations `i` to `v`, `2` and `jr` with `junior` and `jnr`, `&`, the European titles below, and the degrees and salutations every country's data writes alike), a word joining it where it harms no language and would otherwise be duplicated into every language's file — 2026-10-15/16; 2026-10-18 #737; 2026-10-19 #749; 2026-10-19 #750, title kinds; 2026-11-02 #1005 (Derek); 2026-11-03 #1005, the strict-gap batches (Derek). - The default loads every language and keeps working for names of any language. Choosing a language narrows it since 3.0's phase 3 (#753): a pack settles only the clashes where its language has a vocabulary reading (`locales.VI` and `locales.MY` excepted: each fragment removes readings of syllables no reading in its file can settle, Vietnamese 2026-11-05 #1108, Burmese decisions/vocabulary-collisions' 2026-11-19 #1231 entry), a strict choice reads only the chosen languages' files, `mul.toml` and native-script words' readings as a plain choice of the same languages keeps them (name readings included), and a pack's preferred reading can outrank one a shape rule derives — 2026-10-15/16; 2026-10-30 #753, file-strict; 2026-11-02 #1005 (Derek); 2026-11-07 #1148. -- `e`, `y` and `i` stay in the default; choosing a language settles their one-case fork for that language's own reading, `may_be_initial` not holding on a chosen file's conjunction, as `locales.PT` and `locales.PT_BR` do for `e` — 2026-10-15/16; 2026-10-29 #753, phase 3b; 2026-10-30 #753, phase 3g. +- `e`, `y` and `i` stay in the default; choosing a language settles their one-case fork for that language's own reading, `may_be_initial` not holding on a chosen file's conjunction, as `locales.PT`, `locales.PT_BR` and `locales.PT_PT` do for `e` — 2026-10-15/16; 2026-10-29 #753, phase 3b; 2026-10-30 #753, phase 3g. - A patronymic field came in 3.0, as a view that names its words without emptying `family`, and the particle kinds already draw the `clan`/`patronymic` line for it: a patronymic is followed by a parent's name, a clan prefix by a family name the lineage shares — 2026-10-15/16; 2026-10-19 #749; 2026-10-28 #754 (Derek); landed as rules/R9, 2026-10-29 #754, sub-phase 4c. - A shipped pack that is only a choice of languages declares no `DEVIATES`, its surface the words its choice changes; `ga` turns on `nic`, `mhic`, `mic` and `uí` as clan particles, `gd` `nic`, and `pt-BR` `sb` as Sobrinho's spelling, while the single letters `f` and `n` are excluded, the pack included, the letter abbreviating a surname more often than the agnomen in the filings that write it — 2026-10-30 #753, phase 3h. - The Breton article `ar` is a reading of `br.toml` written `default = false`, read by a choice of `br` that no pack makes, and `M.` (Monsieur) is excluded, a French choice included, the letter an initial in every name data source measured; fr `père` is read by default (decisions/generational-words), so no French pack ships — 2026-11-03 #658. @@ -18,7 +18,7 @@ The vocabulary was a set of base sets plus marker subsets (`particles` and `part - Of the romanized titles a pack's phase lists, one whose native spelling is a default title turns on unless, counted in persons and pooled across every population measured, names open with it more often than it opens one as the title; a spelling outside the phase's list (`Shreemati`, `Srimati`) stays open until a phase writes it as a reading: `hi` turns on `smt`, `shrimati` and `shriyut`, `bn` `smt`, `shrimati` and `adhyapak` (`shriyut` with no bearer anywhere, `adhyapak` with family-name bearers only, every one where the title claim, acting at the head, does not reach), while `shri`, opening given names in every population measured, stays excluded, and `sushri`, an Odia given name, is a `default = false` salutation in hi.toml with the Odia name declared in or.toml, so the plain `hi` choice, made for data that holds those names, reads it as a title only inside a title phrase and a strict one as the title (decisions/indic-honorifics, 2026-11-03 #345/#870) — 2026-10-30 #753, phase 3e. - A language pack is a choice of languages on `Locale.languages` selecting which readings compile, a tag choosing its own file and its ancestors', and a reading index, loaded on its first lookup, carries the languages to run time; strict is file-strict, the chosen files, `mul.toml` and native-script words' readings only, `und.toml` not among them, so it needs no 3i; third-party language files are deferred — 2026-10-27 #753 (Derek); 2026-10-29 #753, phase 3a (Derek); 2026-10-29 #753, phase 3b; 2026-10-30 #753, file-strict; 2026-11-02 #1005 (Derek); 2026-11-07 #1148. - A strict choice is `parser_for(..., strict=True)` over the whole choice, filtering the base's readings as a plain choice does, the caller's own edits applying after it, and a chained call keeping its base's strictness unless it passes `strict`, an explicit `False` on a strict base raising and an explicit `True` making a plain base's choice strict; a strict call whose packs choose no language raises; a strict choice accepts a tag whose file holds no reading, which a plain one refuses as changing nothing; a bare choice has no constructor, no `locales.choose`; and the words strict ungates are derived against the plain choice of the same tags and held to a reviewed set by a test — 2026-10-31 #753, phase 3j; 2026-11-02 #754, sub-phase 4i-c. -- A choice is matched without regard to case, a tag whose file does not exist selects its ancestors' (`pt-PT` selects `pt`), `mul` and `und` are no language to choose, and a vocabulary reading turned on also prefers (a name reading never does, decision 15), so `de`'s generation `i` drops `ca`'s and `pl`'s conjunction under a `de` choice; the `Lexicon` records its choice, so that a choice chained through `base=` unions with the base's, and a caller's own edits apply after the choice, plain or strict, in the order written, a pack's fragment joining before the caller's lexicon — 2026-10-29 #753, phase 3b; 2026-11-02 #754, the `Lexicon` surface (Derek); 2026-11-02 #754, sub-phase 4i-c. +- A choice is matched without regard to case, a tag whose file does not exist selects its ancestors' (`pt-AO` selects `pt`; `pt-PT`, whose file holds a `[rules]` table and no reading, selects `pt` the same way, decisions/O6 2026-11-19), `mul` and `und` are no language to choose, and a vocabulary reading turned on also prefers (a name reading never does, decision 15), so `de`'s generation `i` drops `ca`'s and `pl`'s conjunction under a `de` choice; the `Lexicon` records its choice, so that a choice chained through `base=` unions with the base's, and a caller's own edits apply after the choice, plain or strict, in the order written, a pack's fragment joining before the caller's lexicon — 2026-10-29 #753, phase 3b; 2026-11-02 #754, the `Lexicon` surface (Derek); 2026-11-02 #754, sub-phase 4i-c. - A reading right in its own language and wrong only as a default, because another language written in the same script collides with it, is written `default = false` in its file, never excluded, so that after the packs an exclusion means wrong everywhere: cs `st` since phase 2h, and cs `ml`, hr, sk and sl `ml` and `st` since 3c (fr `père`, converted with them, is read by default since 2026-11-03, a collision inside French), the rest in their packs' PRs — 2026-10-27 #753 (Derek); 2026-10-29 #753, phase 3c. - A name reading written `default = false` derives no marker in the default and counts for no check guarding the default's compile; a particle whose word's only `given` readings are off is refused until a pack needs one — 2026-10-29 #753, phase 3a. - A caller configures vocabulary by reading, `Lexicon` deriving the sets and gates the build derives, and the compiled sets become internal in 3.0 — 2026-10-28 #754, the `Lexicon` surface (Derek). @@ -423,7 +423,7 @@ Open: [#1145](https://github.com/derek73/python-nameparser/issues/1145), the dis - **The phase 3d entry's question, a `given` reading of `श्री` in hi.toml or bn.toml, is answered no.** For Hindi the evidence is CLDR's: of the four renderings the phase 3d entry found moving under `ne`, two are `hi` (`givenFirst` and `surnameFirst`), one `kok` and one `mr` (`givenFirst` each), each writing `श्री` as the title, so `श्री` stays a title under `hi` and `hi.toml`'s `श्री` note stays true. For Bengali the answer is unmeasured: no CLDR rendering and no committed corpus holds `শ্রী` (2026-10-30), so `bn` keeps the default's reading of it, a title, by default rather than by measurement. - **Open: `shri`, and the romanizations outside 3e's list.** Whether `shri` takes phase 2j's route in the default, a `given` reading beside its title one so that it is a title only inside a title phrase, is default work this entry does not do; its counts are on its exclusion. CLDR's `hi_Latn` writes the salutation `Shree`, the spelling nepal-candidates romanizes `श्री` as a name word in 191 pairs (the phase 3d entry); nepal-candidates' romanized names open with `Shreemati` 47 times, three times `Shrimati`'s 16, 6 of them paired with `श्रीमति`, 41 of the 47 paired with `श्रीमती` and none opening an ORCID given box, and with `Srimati`, Bengali's romanization of শ্রীমতী, 12 times, 11 of them paired with the salutation (`श्रीमती` 10, `श्रीमति` 1), against 4 ORCID given boxes holding it alone (Naik, Nayak, Ghosal, Basu), the direction `shrimati`'s counts take; none was measured as a reading here. 18 nepal-candidates pairs open their Devanagari with `श्रीमति`, short i, a spelling of `श्रीमती` hi.toml does not list. - **Recompute:** the commands above from a checkout of this change, against a detached checkout of master; FEC's figure with `snapshot.py --local fec-individuals --base` on that tree; the PSC, ORCID and PatentsView figures with the scratch scorer of the phase 3h entry (`local_agreement.read` per record under `Parser()` and `parser_for(pack)`, over the records whose name holds a word of `changed_words(selected(pack.languages))`), run on a tree that removes `shri`'s exclusion from hi.toml and adds `shri` and `sushri` to hi.toml, and `shri` to bn.toml, as `salutation` readings `default = false` (the build refuses the reading while the exclusion stands); the ORCID box counts by reading `ORCID_2025_10_summaries.v1.jsonl.gz` from the cache and counting the boxes whose first word folds to the word. -- **2026-10-30 #753, phase 3g (its titles' `default = false`, all but `doña`'s, superseded by the 2026-11-06 #1115, the pack titles entry, which is the default change this entry left for later) — THE SPANISH AND PORTUGUESE PACKS, `locales.ES` AND `locales.PT`: THE TITLES THAT LEAD A NAME WITHOUT A COMPLEMENT TURN ON; `don`, `dona`, `dom` AND `maestro` STAY OUT, MEASURED; `sr` KEEPS ITS GENERATION AND `h` IS EXCLUDED; `ES` READS TWO FAMILY NAMES; NO TITLE-RUN CONNECTIVE; THE DEFAULT DOES NOT MOVE.** Carries out 3g of item 11 of the 2026-10-27 #753 entry. +- **2026-10-30 #753, phase 3g (its titles' `default = false`, all but `doña`'s, superseded by the 2026-11-06 #1115, the pack titles entry, which is the default change this entry left for later; its `locales.PT` waiting for a Portuguese given-name list answered by decisions/O6's 2026-11-19 #1453 entry: `locales.PT` stays off, `locales.PT_BR` and a new `locales.PT_PT` turn the switch on with a list) — THE SPANISH AND PORTUGUESE PACKS, `locales.ES` AND `locales.PT`: THE TITLES THAT LEAD A NAME WITHOUT A COMPLEMENT TURN ON; `don`, `dona`, `dom` AND `maestro` STAY OUT, MEASURED; `sr` KEEPS ITS GENERATION AND `h` IS EXCLUDED; `ES` READS TWO FAMILY NAMES; NO TITLE-RUN CONNECTIVE; THE DEFAULT DOES NOT MOVE.** Carries out 3g of item 11 of the 2026-10-27 #753 entry. - **What each pack turns on.** `locales.ES` chooses `es`, turns `two_family_names` on through es.toml's `[rules]` table (sub-phase 4f's schema, `PACK_RULES` gaining `es`), and carries `nameparser/locales/_es_given_names.py`'s list as its lexicon fragment, `Lexicon(given_names=GIVEN_NAMES)`, as `locales.ZH` carries its surnames; the switch and the list are decisions/O6's, and the decision to turn them on, made in chat, and its measurement are decisions/O6's 2026-10-30 phase 3g entry, which also records why `two_given_names` stays opt-in (decisions/O7's). `locales.PT` chooses `pt`, with an empty fragment and no patch, until a Portuguese given-name list exists (the same entry). es.toml writes `default = false` the academic readings `lic`, `licenciado`, `licenciada`, `lcdo`, `lcda`, `ingeniero`, `ingeniera`, `arq`, `mtro`, `mtra`, `doctora`, `profesor`, `profesora` and the salutation `doña`; pt.toml `doutor`, `doutora`, `professora` and `profa`. Each is `default = false` because phase 3 moves no default parse (item 12), not because another language collides with it; whether some belong in the default is a default change, left for one. Counts are on each reading, from `tools/name_usage.py --boxes` and a count of the names in every local corpus that open with the word or open the part after a comma with it. - **Excluded, measured, the packs included:** `don` (es.toml), `dona` and `dom` (pt.toml), each a given name that opens more names than the title does, Spanish and Portuguese data included (the phase 3e criterion, counted in persons over every population measured): `Don` opens 80 ClinicalTrials.gov officials' names, 86 PatentsView inventors', 11 PSC filers', 2 of tse-donors' 3 and 2,819 FEC given parts after the family comma, against jrc-names' 874 openers that mix the name and the Italian clergy's title; `Dona` and `Dom` alike (their reasons hold the counts). `maestro` is a Spanish and Italian family name (ORCID's family box 43 records in Spain) whose form of address is written `Mtro.`. `doña` ships though it is a family name in Spain (ORCID's family box 18): the title claim acts in front, as for `graf` and `herra` (rules/H1's Accepted clause on a title word borne as a name, rarely as the first word of one), so where a name opens with the family name the pack gives it to the title, accepted costs that no local corpus name takes (2026-10-30): before a family comma with a name word behind it (rules/H6), `Doña Ortega, María` reads title `Doña`, family `Ortega` where the default gives family `Doña Ortega`, and under `FAMILY_FIRST` `Doña Ortega Ana` reads title `Doña`, family `Ortega`, given `Ana`, where the default gives family `Doña`. `ing` stays excluded (mul.toml): written with its period it already reads as a title at the head by rules/H2's shape. - **`sr` keeps its generation under both packs.** The phase 3h entry left it Open for 3g: es.toml and pt.toml each held only a salutation reading of `sr`, so a choice preferred it and English's generation left, and a trailing `Sr` read as the family name (`Gary Holloway Sr` family `Sr`, PSC 12 filers, 10 of them Filipino by nationality, their names written in Spanish, and 1 American and 1 English). Each file now writes a `generation` reading beside the salutation, names written in Spanish and Portuguese writing the English generation too, so the choice leaves `sr` a dual position decides, as the default reads it, and `sr` leaves both choices' deviation surfaces; under `pt-BR` too. diff --git a/docs/design/mechanisms.md b/docs/design/mechanisms.md index 9d1c11553..c4e0b21ef 100644 --- a/docs/design/mechanisms.md +++ b/docs/design/mechanisms.md @@ -348,7 +348,7 @@ rules/O8's letters are the same shape at the family's other edge: the family wri **Contract statement.** A locale pack is pure data — a choice of languages, a Lexicon fragment of ADDITIONS (two packs' of removals, `locales.VI`'s and `locales.MY`'s, below) and a Policy patch — applied by parser_for, a shipped pack's patch compiled from its language file's `[rules]` table where one is written, each key the `Policy` field of its name: the packs' languages union with the base's recorded choice into one choice, recorded on the `Lexicon`, which selects among the base's shipped readings by the file each sits in, the fragments join in pack order and the caller's lexicon after them, its own readings applying after the choice, and the patches fold in order (set-valued fields union, `script_orders` merges by script, scalars override); packs contain no code paths of their own. A vocabulary pack's deviations are derived from the reading index, the words whose compiled readings its choice changes; a policy or segmentation pack declares its own in its docstring and `DEVIATES`. -**How it works.** What is policy for every language (an order constant) is policy, not pack data; packs are lowercase modules exposing uppercase constants; a pack error is wrapped with the pack's code (rule D2). A choice changes the base's readings only by selection, never by a list of removals (a pack's fragment may remove, as a caller's lexicon may, and two shipped packs' do: `locales.VI` takes out the particle, connective and credential readings of the Vietnamese syllables its order would otherwise chain or cut off, `Van` in `Nguyen Van Anh`, a settling no reading in its file can do, decisions 6 and 15 of decisions/vocabulary-model, bent there on 2026-11-05 #1108; `locales.MY` the particle readings of the Burmese syllables, `San` in `Aung San Win`, and `do`'s credential reading, which the particle chain had kept from ending `AUNG SAN DO`, decisions/vocabulary-collisions, 2026-11-19 #1231): a chosen language's `default = false` readings join; on a word a chosen language holds a vocabulary reading of, other languages' vocabulary readings leave, save `mul.toml`'s; and a chosen language's conjunction loses `may_be_initial`, its clash with the initial being a shape reading a preference outranks, which is how a `pt` choice drops `e` from `conjunctions_ambiguous` (decisions/vocabulary-model, 2026-10-27 #753, items 1, 2 and 7; built 2026-10-29, phase 3b). A strict choice, `parser_for(..., strict=True)`, selects by file alone: only the chosen files, `mul.toml` and native-script words' readings as a plain choice of the same languages keeps them (name readings included) compile, `und.toml`'s readings leaving with every other file's (decisions/vocabulary-model, 2026-10-30 #753, file-strict; built 2026-10-31, phase 3j; `mul.toml` kept since 2026-11-02 #1005). So a bad default is routed around only by choosing the language whose reading is right, which is why #342-class fixes still change shipped vocabulary. The choice filters the base's shipped readings and the caller's own `add` and `remove` calls apply after it, so a choice never drops a caller's word, and one that clashes with a reading the choice turns on is refused at `parser_for`, naming the edit; a lexicon built from `Lexicon.empty()` holds no shipped reading, so a choice turns none on in it; a pack choosing no language leaves the base's exactly as it was. The choice is recorded on the `Lexicon`, so `parser_for(EN, base=parser_for(PT))` chooses both, as `parser_for(PT, EN)` does (decisions/vocabulary-model, 2026-11-02 #754, the `Lexicon` surface, items 3 and 4; built 2026-11-02, sub-phase 4i-c). Pure data means a pack can be audited: a vocabulary pack's whole content is its tag, but what it changes reaches other files too, prefer dropping their readings of its words (a `de` choice drops `ca.toml`'s conjunction `i`), so the audit is the derived surface, `changed_words`, not the pack's file alone. A country pack is the same data with a region tag: `locales.ES_AR` chooses `es-AR`, which selects `es.toml` by ancestry until a reading is Argentina's own, names its language's `[rules]` (`rules_patch("es")`) rather than inheriting them, and carries its own lexicon fragment, so stacked on its language's pack it reads as itself where its fragment holds the language pack's (decisions/O6, 2026-11-04). +**How it works.** What is policy for every language (an order constant) is policy, not pack data; packs are lowercase modules exposing uppercase constants; a pack error is wrapped with the pack's code (rule D2). A choice changes the base's readings only by selection, never by a list of removals (a pack's fragment may remove, as a caller's lexicon may, and two shipped packs' do: `locales.VI` takes out the particle, connective and credential readings of the Vietnamese syllables its order would otherwise chain or cut off, `Van` in `Nguyen Van Anh`, a settling no reading in its file can do, decisions 6 and 15 of decisions/vocabulary-model, bent there on 2026-11-05 #1108; `locales.MY` the particle readings of the Burmese syllables, `San` in `Aung San Win`, and `do`'s credential reading, which the particle chain had kept from ending `AUNG SAN DO`, decisions/vocabulary-collisions, 2026-11-19 #1231): a chosen language's `default = false` readings join; on a word a chosen language holds a vocabulary reading of, other languages' vocabulary readings leave, save `mul.toml`'s; and a chosen language's conjunction loses `may_be_initial`, its clash with the initial being a shape reading a preference outranks, which is how a `pt` choice drops `e` from `conjunctions_ambiguous` (decisions/vocabulary-model, 2026-10-27 #753, items 1, 2 and 7; built 2026-10-29, phase 3b). A strict choice, `parser_for(..., strict=True)`, selects by file alone: only the chosen files, `mul.toml` and native-script words' readings as a plain choice of the same languages keeps them (name readings included) compile, `und.toml`'s readings leaving with every other file's (decisions/vocabulary-model, 2026-10-30 #753, file-strict; built 2026-10-31, phase 3j; `mul.toml` kept since 2026-11-02 #1005). So a bad default is routed around only by choosing the language whose reading is right, which is why #342-class fixes still change shipped vocabulary. The choice filters the base's shipped readings and the caller's own `add` and `remove` calls apply after it, so a choice never drops a caller's word, and one that clashes with a reading the choice turns on is refused at `parser_for`, naming the edit; a lexicon built from `Lexicon.empty()` holds no shipped reading, so a choice turns none on in it; a pack choosing no language leaves the base's exactly as it was. The choice is recorded on the `Lexicon`, so `parser_for(EN, base=parser_for(PT))` chooses both, as `parser_for(PT, EN)` does (decisions/vocabulary-model, 2026-11-02 #754, the `Lexicon` surface, items 3 and 4; built 2026-11-02, sub-phase 4i-c). Pure data means a pack can be audited: a vocabulary pack's whole content is its tag, but what it changes reaches other files too, prefer dropping their readings of its words (a `de` choice drops `ca.toml`'s conjunction `i`), so the audit is the derived surface, `changed_words`, not the pack's file alone. A country pack is the same data with a region tag: `locales.ES_AR` chooses `es-AR`, which selects `es.toml` by ancestry until a reading is Argentina's own, names its language's `[rules]` (`rules_patch("es")`) rather than inheriting them, and carries its own lexicon fragment, so stacked on its language's pack it reads as itself where its fragment holds the language pack's (decisions/O6, 2026-11-04). A country that turns on a rule its language leaves off writes the table in a file of its own, which may hold nothing else: `locales.PT_BR` reads `pt-BR.toml`'s and `locales.PT_PT` `pt-PT.toml`'s, while `locales.PT` reads none, and the two country packs share one lexicon fragment (decisions/O6, 2026-11-19). **Lives in.** nameparser/locales/ (packs), nameparser/_parser.py (parser_for, the one applier), nameparser/_lexicon.py (the compile under a recorded choice, `_chosen_pool` and `_built`), nameparser/_reading_index.py (the selection, `choose`, and the derived surface, `changed_words`), nameparser/_locale.py (`rules_patch`, a file's compiled `[rules]` as a patch) and tools/vocab/build.py (`RULE_KEYS`, the rules a file may turn on, and `PACK_RULES`, the files the shipped packs read; decisions/vocabulary-model, 2026-10-29 4f). A rule a file turns on is a `Policy` field; a new rule kind is a core change, never code in a pack: a new `Policy` field (with `ADDED_IN`), a row in build.py's `RULE_KEYS` and in `_locale._RULE_VALUES`, and a mechanisms.md entry of its own for the rule kind. diff --git a/docs/design/rules/S11-suffix-word-that-is-also-a-name.md b/docs/design/rules/S11-suffix-word-that-is-also-a-name.md index 907584533..14265087e 100644 --- a/docs/design/rules/S11-suffix-word-that-is-also-a-name.md +++ b/docs/design/rules/S11-suffix-word-that-is-also-a-name.md @@ -33,7 +33,8 @@ "JOSE CARLOS SILVA SB" [pt_br] → suffix="SB" "JOSE CARLOS SILVA SB" → family="SB" · boundary "Ana SB" [pt_br] → family="SB" · boundary -"JOSE CARLOS SILVA F" [pt_br] → family="F" · boundary +"JOSE CARLOS F" [pt_br] → family="F" · boundary +"JOSE CARLOS SILVA F" [pt_br] → family="SILVA F" · boundary "Pedro Alves Sobr." → suffix="Sobr." "Pedro Alves Neto, PhD" → suffix="Neto, PhD" "Pedro Alves Neto Júnior" → suffix="Neto Júnior" diff --git a/docs/languages.rst b/docs/languages.rst index e832f872c..fd2833823 100644 --- a/docs/languages.rst +++ b/docs/languages.rst @@ -27,8 +27,8 @@ Dutch particles, and Burmese names. Other languages are described where their me - **Nepali** (``ne``): :ref:`nepali-given-names`. - **Irish and Scottish Gaelic** (``ga``, ``gd``): :ref:`gaelic-clan-particles`. -- **The words the Portuguese packs turn on** (``pt``, ``pt_br``): - :ref:`portuguese-packs`. +- **The words the Portuguese packs turn on** (``pt``, ``pt_br``, + ``pt_pt``): :ref:`portuguese-packs`. - **Chinese, Japanese and Korean** (``zh``, ``ja``, and Korean with no pack): :ref:`east-asian-names`. @@ -287,10 +287,12 @@ Spanish and Portuguese titles ----------------------------- Turn on ``es`` when your data is Spanish names, ``es_ar`` when it is -Argentine ones, and ``pt`` when it is Portuguese ones. The default -already reads the titles described below, save two that ``es`` turns -on; the larger change is two family names, which the Spanish packs -read and ``pt`` leaves off. +Argentine ones, ``pt_br`` when it is Brazilian ones, ``pt_pt`` when it +is names from Portugal, and ``pt`` when it is Portuguese names from +anywhere else or from several countries. The default already reads the +titles described below, save two that ``es`` turns on; the larger +change is two family names, which the Spanish packs, ``pt_br`` and +``pt_pt`` read and ``pt`` leaves off. Titles ~~~~~~ @@ -379,7 +381,7 @@ is never taken for one written with n: ``Oña`` is a surname, though >>> spain.parse("Juan Oña Pérez").family 'Oña Pérez' -A compound given name stays opt-in under the Spanish packs and ``pt`` +A compound given name stays opt-in under the Spanish and Portuguese packs alike (``two_given_names``, see :ref:`two-given-names`): people filling a form with a middle-name box put the second given name there. @@ -432,11 +434,39 @@ reads fewer researchers' names right than ``es``'s does. .. _portuguese-two-family-names: -Portuguese: why ``pt`` leaves the switch off -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Portuguese: two family names in Brazil and Portugal +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Portuguese names write the mother's family name before the father's, +and Brazilian and Portuguese names often carry both. Turn on ``pt_br`` +for Brazilian names and ``pt_pt`` for names from Portugal: each reads +two family names, guarded by a list of about 700 Portuguese given +names that the switch leaves where they stand: -Where reading two family names helps your Portuguese data, turn it on -beside the pack, on the base parser: +.. doctest:: + + >>> brazil = parser_for(locales.PT_BR) + >>> portugal = parser_for(locales.PT_PT) + >>> parse("Tiago Barros Queiroz").family + 'Queiroz' + >>> brazil.parse("Tiago Barros Queiroz").family + 'Barros Queiroz' + >>> portugal.parse("Ana Beatriz Costa").family + 'Costa' + +The list is measured on ORCID's researchers in Portugal and Brazil, +from the words their holders type in the given-name box at least 70% +of the time. A word it lacks is taken all the same, which is the +switch's cost (``Ana Zélia Costa`` gives family ``Zélia Costa`` under +either pack). + +``pt``, the pack chosen by language, leaves the switch off, the +reverse of Spanish, where the language pack carries it. ``pt`` serves +every Portuguese-speaking country, and the switch helps some and sinks +others: Angolan and Mozambican names lose under it, even with the +list, which holds few of the given names written there. Where reading +two family names helps your Portuguese data from another country, +turn it on beside ``pt``, or choose ``pt_pt``: .. doctest:: @@ -448,19 +478,76 @@ beside the pack, on the base parser: >>> pt_two.parse("Tiago Barros Queiroz").family 'Barros Queiroz' -``pt`` does not turn it on, because it serves every -Portuguese-speaking country and the switch helps some and sinks -others: among ORCID's researchers it mends about two names for each it -breaks in Portugal (71.5% → 83.2%) and three in Brazil (49.5% → -74.4%), but sinks Angola (75.9% → 57.3%) and Mozambique (85.2% → -50.2%), and a Portuguese given-name list to guard it does not exist -yet. +A family of three surnames still keeps its first as a middle name +under both packs (``Leonardo Mirandela Gomes Paz`` gives middle +``Mirandela``, family ``Gomes Paz``): the switch takes one word. +Among ORCID's Brazilian researchers about one name in ten is written +that way. + +Measured effect: Portuguese +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The figures are of ORCID's researchers, names agreeing in every box +with the filer, on records the list was not built from: -Whether it helps Portuguese or Brazilian data depends on who split the -names: it gains on names their bearers split themselves, as ORCID's -are, and costs about 5 points on names filed through a form, as the UK -company register's Portuguese filers are (61.1% → 56.1%). -:ref:`portuguese-packs` says what ``pt`` and ``pt_br`` do turn on. +.. list-table:: + :header-rows: 1 + :widths: 40 20 20 20 + + * - Where the researcher works + - Default and ``pt`` + - ``pt_br`` or ``pt_pt`` + - Records + * - Portugal + - 72.1% + - 89.7% + - 2,923 + * - Brazil + - 50.3% + - 79.8% + - 2,850 + * - Cape Verde + - 61.5% + - 80.5% + - 563 + * - São Tomé and Príncipe + - 50.4% + - 71.1% + - 121 + * - Guinea-Bissau + - 66.8% + - 72.3% + - 220 + * - Timor-Leste + - 64.0% + - 67.1% + - 495 + * - Angola + - 76.4% + - 65.3% + - 2,861 + * - Mozambique + - 85.6% + - 67.2% + - 2,853 + +So Cape Verdean and São Toméan lists read better under ``pt_pt`` than +under ``pt``, and Angolan and Mozambican lists worse. + +Whether the switch helps also depends on who split the names. It +gains most on names their bearers split themselves, as ORCID's are. +It costs Brazilian inventors on US patents: their filers usually give +one surname as the family name and put the rest of the name in the +first-name box, and against that split, over all 15,029 Brazilian +records in the data, 75.7% read right by default or under ``pt`` and 60.2% +under ``pt_br``, while Portuguese inventors gain under ``pt_pt`` +(57.6% → 66.1%). Most of the Brazilian names it breaks hold a second +surname among the given names (``Eder Ferreira`` / ``Rangel``, read +family ``Ferreira Rangel``). So choose ``pt_br`` or ``pt_pt``, by +country, for names whose family part is written whole, and keep ``pt`` for data +filed with a single surname as the family name. +Among the UK company register's filers the switch gains for +Portuguese (59.2% → 62.8%) and Brazilian (53.7% → 62.9%) nationals. Measured effect: Spanish ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -483,7 +570,8 @@ with the filer: The dated figures, and those for Portuguese above, are in ``docs/design/decisions/O6-two-family-names.md``; the Argentine ones -are from its entry on ``locales.ES_AR``. +are from its entry on ``locales.ES_AR``, the Portuguese ones from its +entry on ``locales.PT_BR`` and ``locales.PT_PT``. .. _romanized-indic-titles: diff --git a/docs/locales.rst b/docs/locales.rst index 4e204dfe3..901af09dd 100644 --- a/docs/locales.rst +++ b/docs/locales.rst @@ -138,8 +138,8 @@ Read that precisely: a shape is a pattern, not a language, so a pack can act on a name from a tradition it was not written for. A broad shape covers much: -- ``es``, ``es_ar``, ``cs`` and ``sk`` may read any name of three words - differently. +- ``es``, ``es_ar``, ``cs``, ``sk``, ``pt_br`` and ``pt_pt`` may read + any name of three words differently. - ``vi``, whose name order is its shape, may read any name differently: the order moves every name a family comma does not fix, and its titles and removed readings reach the comma names too. @@ -188,7 +188,7 @@ look one up dynamically by its lowercase code with .. doctest:: >>> locales.available() - ('ar', 'bn', 'cs', 'es', 'es_ar', 'ga', 'gd', 'he', 'hi', 'hr', 'ja', 'mn', 'my', 'ne', 'nl', 'pt', 'pt_br', 'ru', 'sk', 'sl', 'tr_az', 'vi', 'zh') + ('ar', 'bn', 'cs', 'es', 'es_ar', 'ga', 'gd', 'he', 'hi', 'hr', 'ja', 'mn', 'my', 'ne', 'nl', 'pt', 'pt_br', 'pt_pt', 'ru', 'sk', 'sl', 'tr_az', 'vi', 'zh') >>> locales.get("ru") is locales.RU True @@ -319,17 +319,25 @@ says which parts each pack is made of. opening the family name. See :ref:`dutch-particles`. - ``Jan ten Brink`` → family ``ten Brink`` * - ``pt`` - - Portuguese + - Portuguese, from any country - Chooses ``pt``, which settles Portuguese's clashes its way (``do`` a particle, not the DO credential). See :ref:`portuguese-packs`. - ``Maria da Piedade Costa`` → middle ``da Piedade`` * - ``pt_br`` - Brazilian Portuguese - - Chooses ``pt-BR``, and with it ``pt``, and turns on ``SB``, the - agnomen Sobrinho as Brazilian filings abbreviate it. See - :ref:`portuguese-packs`. - - ``JOSE CARLOS SILVA SB`` → suffix ``SB`` + - Chooses ``pt-BR``, and with it ``pt``, turns on ``SB``, the + agnomen Sobrinho as Brazilian filings abbreviate it, and reads + two family names, guarded by a list of Portuguese given names. + See :ref:`portuguese-packs` and :ref:`portuguese-two-family-names`. + - | ``JOSE CARLOS SILVA SB`` → suffix ``SB`` + | ``Tiago Barros Queiroz`` → family ``Barros Queiroz`` + * - ``pt_pt`` + - Portuguese from Portugal + - ``pt`` with two family names and ``pt_br``'s given-name list. See + :ref:`portuguese-two-family-names`. + - ``Rui Sousa Pinto`` → family ``Sousa Pinto``, where ``pt`` gives + ``Pinto`` * - ``ru`` - East Slavic names in formal order - Detects the family/given/patronymic shape by the patronymic's @@ -384,7 +392,7 @@ says what it can change: - Policy fields - Word list * - ``ar``, ``bn``, ``ga``, ``gd``, ``he``, ``hi``, ``hr``, ``nl``, - ``pt``, ``pt_br``, ``sl`` + ``pt``, ``sl`` - yes - none - none @@ -392,7 +400,7 @@ says what it can change: - yes - ``two_family_names`` - none - * - ``es``, ``es_ar`` + * - ``es``, ``es_ar``, ``pt_br``, ``pt_pt`` - yes - ``two_family_names`` - the given names that switch leaves where they stand @@ -610,8 +618,8 @@ costs the other languages' readings of those words. Most of these packs are described in :doc:`languages`, where the table above links each. Two groups are described here: the Irish and Scottish Gaelic packs (:ref:`gaelic-clan-particles`), and the Portuguese ones, -which turn on ``da Piedade`` and, in ``pt_br``, ``SB`` -(:ref:`portuguese-packs`). +which turn on ``da Piedade``, in ``pt_br`` ``SB``, and in ``pt_br`` +and ``pt_pt`` two family names (:ref:`portuguese-packs`). .. _gaelic-clan-particles: @@ -645,16 +653,17 @@ The choice costs English's reading of ``MC``: under ``ga`` and .. _portuguese-packs: -Portuguese and Brazilian Portuguese (``pt``, ``pt_br``) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Portuguese (``pt``, ``pt_br``, ``pt_pt``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Turn on ``pt`` for Portuguese names from any country, and ``pt_br`` for -Brazilian ones: ``pt_br`` chooses ``pt-BR``, and with it ``pt``, so it -does everything ``pt`` does. Neither reads two family names -(:ref:`Spanish and Portuguese titles ` says -why, and how to turn that on). +Turn on ``pt`` for Portuguese names from any country, ``pt_br`` for +Brazilian ones and ``pt_pt`` for names from Portugal: ``pt_br`` chooses +``pt-BR`` and ``pt_pt`` ``pt-PT``, each with ``pt``, so each does +everything ``pt`` does. ``pt_br`` and ``pt_pt`` also read two family +names, and ``pt`` does not; :ref:`portuguese-two-family-names` says +why, and how to turn the switch on beside ``pt``. -``pt`` and ``pt_br`` turn on a Portuguese given name written +The three packs turn on a Portuguese given name written behind a particle that is too rare to read by default (``da Piedade``), so the phrase reads as a middle name, as ``das Graças`` does by default (see :ref:`two-given-names`): @@ -677,16 +686,17 @@ where the name keeps a family name without it (``Ana SB`` keeps family >>> parse("JOSE CARLOS SILVA SB").family 'SB' - >>> brazil = parser_for(locales.PT_BR).parse("JOSE CARLOS SILVA SB") - >>> brazil.family, brazil.suffix + >>> sobrinho = parser_for(locales.PT_BR).parse("JOSE CARLOS SILVA SB") + >>> sobrinho.family, sobrinho.suffix ('SILVA', 'SB') The choices cost the other languages' readings of the words they settle: -- **Under pt and pt_br,** the words read as ``pt`` reads them: ``do`` is +- **Under pt, pt_br and pt_pt,** the words read as ``pt`` reads them: ``do`` is the particle, not the DO credential, so ``John Smith DO`` gives - family ``DO``. ``Sr`` keeps both readings, *Senhor* in front and + family ``DO`` under ``pt`` (``Smith DO`` under ``pt_br`` and + ``pt_pt``, which read two family names). ``Sr`` keeps both readings, *Senhor* in front and "Senior" behind, as in the default, under ``es`` too. - **Under pt_br,** a written S.B. degree reads as Sobrinho (``Howard Gordon, MD SB`` fills ``generation`` with ``SB``). @@ -895,7 +905,7 @@ of four ways: - **A tag no vocabulary file holds**, itself or any language it belongs to (``xx``), raises ``ValueError`` at :func:`~nameparser.parser_for`, naming the tags that have a file. -- **A region or other subtag of a language that has a file** (``pt-PT``) +- **A region or other subtag of a language that has a file** (``pt-AO``) is accepted and reads that language's file, there being none of its own. - **A language whose file holds no reading a parse reads yet** diff --git a/docs/migrate.rst b/docs/migrate.rst index f79e6f561..de55c3eeb 100644 --- a/docs/migrate.rst +++ b/docs/migrate.rst @@ -2158,6 +2158,42 @@ reports the fork, as ``van`` does: Brink`` gives family ``ten Brink``); the default parse of a name holding ``ten`` is unchanged. +Two family names under locales.PT_BR +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``locales.PT_BR`` reads two family names (``two_family_names``), where +3.0 and 3.1 read the first as a middle name; a second given name on +its Portuguese given-name list stays where it stands. ``locales.PT`` +is unchanged, and ``locales.PT_PT``, new in 3.2, reads two family +names, with the same list, as ``locales.PT_BR`` does: + +.. doctest:: + + >>> brazilian = parser_for(locales.PT_BR) + >>> souza = brazilian.parse("Ana Souza Lima") + >>> souza.middle, souza.family + ('', 'Souza Lima') + >>> brazilian.parse("Ana Beatriz Costa").family + 'Costa' + >>> parser_for(locales.PT).parse("Ana Souza Lima").family + 'Lima' + +To keep the 3.1 reading, turn the switch off on top of the pack: + +.. doctest:: + + >>> import dataclasses + >>> as_31 = parser_for(locales.PT_BR) + >>> as_31 = dataclasses.replace( + ... as_31, policy=dataclasses.replace(as_31.policy, two_family_names=False)) + >>> as_31.parse("Ana Souza Lima").family + 'Lima' + +A ``locales.PT_BR``, or a parser built from it, pickled by 3.1 still +loads, and reads as 3.1's pack did: a pickle holds the pack's values, +not its name. Build the parser again from ``locales.PT_BR`` to read two +family names. + Malaysian a/l, a/p and anak ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/policy.rst b/docs/policy.rst index 5993c7cfa..0e41fc3dc 100644 --- a/docs/policy.rst +++ b/docs/policy.rst @@ -497,9 +497,9 @@ Turn on ``two_family_names`` when the people in your data carry two family names and write both together, after the given names (or first, under a family-first order), and only then: :ref:`What it costs ` shows what it does to -other names. ``locales.ES`` turns it on -together with a list of given names that it holds back (see `Keeping a -given name out of the family`_). +other names. ``locales.ES``, ``locales.ES_AR``, ``locales.PT_BR`` and +``locales.PT_PT`` turn it on together with a list of given names that it holds back (see +`Keeping a given name out of the family`_). In Spain and most of Latin America a person carries two family names, the father's first and then the mother's, and writes both after the @@ -602,7 +602,10 @@ The field is empty by default, so you supply the list for your data, or choose ``locales.ES``, which turns the switch on and carries 1,000 Spanish given names, a name written with ñ listed with n too (``locales.ES_AR``, for Argentine names, carries about 5,000; see -:ref:`spanish-portuguese-titles`). An entry written without accents +:ref:`spanish-portuguese-titles`), or ``locales.PT_BR`` or +``locales.PT_PT``, which carry about 700 Portuguese ones, a name +written with ç listed with c too (see +:ref:`portuguese-two-family-names`). An entry written without accents matches the word with them: .. doctest:: @@ -705,7 +708,7 @@ Which words are marked: ``de Cássia``, ``de Tarso``). They were chosen by how ORCID researchers filled their own name boxes; the criterion is in ``docs/design/decisions/P10-given-name-a-particle-completes.md``. -- **Under** ``locales.PT`` **and** ``locales.PT_BR`` **only**, a +- **Under** ``locales.PT``, ``locales.PT_BR`` **and** ``locales.PT_PT`` **only**, a Portuguese word too rare to measure (``da Piedade``; see :ref:`language-packs`). - **Not marked**: a phrase too often a surname, as Portuguese diff --git a/docs/release_log.rst b/docs/release_log.rst index fe4ee790c..633ed4df4 100644 --- a/docs/release_log.rst +++ b/docs/release_log.rst @@ -10,6 +10,7 @@ Release Log - **Add locales.MY, a Burmese pack, which reads U and Daw as titles.** ``parser_for(locales.MY).parse("Daw Aung San Suu Kyi")`` gives title ``Daw``, given ``Aung``, middle ``San Suu``, family ``Kyi``, where the default, as 1.4.0 through 3.1.0, gives given ``Daw``, family ``San Suu Kyi``. It reads ``San``, ``La``, ``Van`` and six more as name words, so names holding ``van``, ``da``, ``la`` and the rest lose them as particles (``Jan van Dijk`` gives family ``Dijk``), and an initial ``U.`` can become the title (``Smith, U.`` gives no given name): keep it to Burmese names. See :ref:`burmese-names`. :issue:`1231` - **Fix MD inside a name written in capitals, which read as the degree and took the name behind it.** ``parse("SITI NORA MD YUSRI")`` gives middle ``NORA MD``, family ``YUSRI``, as 1.4.0 through 2.3.0 did, where 2.4.0 through 3.1.0 gave family ``NORA``, suffix ``MD YUSRI``; a name in lower case reads the same way, and both report ``suffix-or-name``, the degree being the other reading. The degree written before a family name in capitals reads so too (``JOHN SMITH MD JONES`` gives family ``JONES``, reported), where ``John Smith MD Jones`` and ``JOHN SMITH M.D. JONES`` keep it. :issue:`1394` - **Fix Emeritus, which read as a given name.** ``parse("Professor Emeritus John Smith")`` gives title ``Professor Emeritus``, given ``John``, where 1.4.0 through 3.1.0 gave title ``Professor``, given ``Emeritus``, middle ``John``; ``Emeritus Professor`` and ``Professor Emerita`` read the same way. ``Emerita`` alone stays the given name, reported, being a given name too. A title other than ``Professor`` or ``Prof`` before it still leaves it a name word (``Bishop Emeritus John Smith`` gives given ``Emeritus``). :issue:`1471` + - **Change locales.PT_BR to read two family names, and add locales.PT_PT, which reads names from Portugal the same way.** ``parser_for(locales.PT_BR).parse("Ana Souza Lima")`` gives family ``Souza Lima``, where 3.0.0 through 3.1.0 gave middle ``Souza``, family ``Lima``; a second given name on the packs' Portuguese given-name list stays where it stands (``Ana Beatriz Costa`` keeps family ``Costa``), and ``locales.PT``, chosen for Portuguese names from any country, is unchanged. :issue:`1453` - **Change locales.ES_AR's given-name list, rewritten from its tool.** ``parser_for(locales.ES_AR).parse("Juan Gerhard Lopez")`` gives family ``Gerhard Lopez``, where 3.0.0 through 3.1.0 gave middle ``Gerhard``; six words leave the list (``Gerhard``, ``Emerita``, ``Zuleyma`` among them) and six join it (``Azhar``, ``Houari``), each joining reading as a middle name where it read as the first family name. :issue:`1471` * 3.1.0 - November 16, 2026 diff --git a/docs/usage.rst b/docs/usage.rst index f40e241a0..cbe8a6e20 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -263,8 +263,8 @@ Two family names: ``surname1`` and ``surname2`` ``surname2`` is the family's second name, where the parse read the family as two: with ``two_family_names`` on -(:ref:`two-family-names`), as the ``es``, ``es_ar``, ``cs`` and ``sk`` -packs turn it on (:doc:`locales`), or for a Chinese name opening with +(:ref:`two-family-names`), as the ``es``, ``es_ar``, ``cs``, ``sk``, +``pt_br`` and ``pt_pt`` packs turn it on (:doc:`locales`), or for a Chinese name opening with two surnames under ``zh`` (:ref:`east-asian-names`), and ``family`` keeps both. Every other name has none, a family comma's and a hyphenated one included: diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index ceddd17a5..b61096402 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -2018,8 +2018,9 @@ class Lexicon: #: dropped (the tilde on n and the cedilla on c kept), so an entry #: written "jose" matches "José" too. No other rule reads it. Empty #: by default, so the switch reads as without it; a caller passes - #: a list of its own, and ``locales.ES`` carries a Spanish list, with - #: the switch on. Added in 3.0. + #: a list of its own; ``locales.ES`` and ``locales.ES_AR`` carry + #: Spanish lists and ``locales.PT_BR`` and ``locales.PT_PT`` a + #: Portuguese one, each with the switch on. Added in 3.0. given_names: frozenset[str] = frozenset() #: Lowercase word -> case mask used by capitalized(): the word's #: own letters and digits, each in the case it takes ("phd" -> diff --git a/nameparser/_locale.py b/nameparser/_locale.py index db4f48cfe..c0becca46 100644 --- a/nameparser/_locale.py +++ b/nameparser/_locale.py @@ -187,9 +187,9 @@ def rules_patch(tag: str) -> PolicyPatch: def deviates_by_two_family_names(name: str) -> bool: """The DEVIATES declaration of a pack whose patch turns on - ``Policy.two_family_names`` (rules/O6), the es, es_ar, cs and sk - packs, and of the given-name list each Spanish pack carries beside - it, which acts only where O6 does. O6 acts only on a name of three + ``Policy.two_family_names`` (rules/O6), the es, es_ar, cs, sk, + pt_br and pt_pt packs, and of the given-name list the es, es_ar, + pt_br and pt_pt packs carry beside it, which acts only where O6 does. O6 acts only on a name of three or more name words, so a name declares that holds three or more words, commas read as spaces, or three or more units counting each run of letters and each word diff --git a/nameparser/_pipeline/_post_rules.py b/nameparser/_pipeline/_post_rules.py index 9f25ee68b..dd15b8abe 100644 --- a/nameparser/_pipeline/_post_rules.py +++ b/nameparser/_pipeline/_post_rules.py @@ -679,8 +679,8 @@ def _take_second_family_name(state: ParseState, 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; locales.ES carries the - # Spanish list, with the switch on) names a word only a given name is, under + # 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). diff --git a/nameparser/_pipeline/_vocab.py b/nameparser/_pipeline/_vocab.py index 425a21bbd..1fcbe78a5 100644 --- a/nameparser/_pipeline/_vocab.py +++ b/nameparser/_pipeline/_vocab.py @@ -2089,7 +2089,7 @@ def given_name_key(text: str) -> str: """`text` folded as `Lexicon.given_names` is matched: the `_normalize` fold, with the accents and the diaeresis dropped and the tilde on n and the cedilla on c kept. tools/es_given_names.py - writes the list with this same fold.""" + and tools/pt_given_names.py write their lists with this same fold.""" out: list[str] = [] for ch in unicodedata.normalize("NFD", _normalize(text)): if unicodedata.combining(ch) and not ( diff --git a/nameparser/config/_index.py b/nameparser/config/_index.py index 7a0cad8df..552a59d88 100644 --- a/nameparser/config/_index.py +++ b/nameparser/config/_index.py @@ -3424,6 +3424,7 @@ 'pl', 'pt', 'pt-BR', + 'pt-PT', 'ro', 'ru', 'sd', diff --git a/nameparser/config/_rules.py b/nameparser/config/_rules.py index cfa26332a..27160bef4 100644 --- a/nameparser/config/_rules.py +++ b/nameparser/config/_rules.py @@ -14,6 +14,8 @@ ('cs', (('two_family_names', True),)), ('es', (('two_family_names', True),)), ('ne', (('initials_as_family', True),)), + ('pt-BR', (('two_family_names', True),)), + ('pt-PT', (('two_family_names', True),)), ('ru', (('patronymic_rules', ('east-slavic',)),)), ('sk', (('two_family_names', True),)), ('tr', (('patronymic_rules', ('turkic',)),)), diff --git a/nameparser/locales/AGENTS.md b/nameparser/locales/AGENTS.md index eca04153d..2a0d79a28 100644 --- a/nameparser/locales/AGENTS.md +++ b/nameparser/locales/AGENTS.md @@ -28,7 +28,7 @@ Write the rules the pack turns on as data, if they are `Policy` fields the vocab 1. Put the table in the pack's language file. 2. List the file in `PACK_RULES` in `tools/vocab/build.py`. 3. Rebuild (`uv run python tools/vocab/build.py`). -4. Give the pack `policy=rules_patch("")` from `nameparser._locale`, as `nameparser/locales/ru.py` does. `PACK_RULES` maps each file holding a table to the pack it is written for; a country pack may read its language's file without a row of its own (`nameparser/locales/es_ar.py` reads `es.toml`'s), so `git grep -l rules_patch -- 'nameparser/locales/*.py'` lists every pack that reads one. +4. Give the pack `policy=rules_patch("")` from `nameparser._locale`, as `nameparser/locales/ru.py` does. `PACK_RULES` maps each file holding a table to the pack it is written for; a country pack may read its language's file without a row of its own (`nameparser/locales/es_ar.py` reads `es.toml`'s), so `git grep -l rules_patch -- 'nameparser/locales/*.py'` lists every pack that reads one. A country that turns a rule its language does not writes the table in its own file, which may hold nothing else (`pt-PT.toml`, read by `nameparser/locales/pt_pt.py`). A pack reads only the table it names, never an ancestor's or a descendant's, so `locales.PT`, which names none (`pt.toml` holds none), is unchanged. A rule the table does not list is a change to the parser, not to a pack. @@ -71,3 +71,4 @@ The shipped packs are the rows of `_REGISTRY` in `nameparser/locales/__init__.py | A choice that changes no word, beside a patch | `nameparser/locales/mn.py` | | A fragment that takes readings out | `nameparser/locales/vi.py` (`nameparser/locales/my.py` beside a choice alone) | | A country pack reading its language's `[rules]` table | `nameparser/locales/es_ar.py` | +| A country pack writing a `[rules]` table its language's file does not, sharing its list with another country's pack | `nameparser/locales/pt_pt.py` | diff --git a/nameparser/locales/__init__.py b/nameparser/locales/__init__.py index 7f4a87a70..ddbaa83a8 100644 --- a/nameparser/locales/__init__.py +++ b/nameparser/locales/__init__.py @@ -40,6 +40,7 @@ "NL": ("nameparser.locales.nl", "NL"), "PT": ("nameparser.locales.pt", "PT"), "PT_BR": ("nameparser.locales.pt_br", "PT_BR"), + "PT_PT": ("nameparser.locales.pt_pt", "PT_PT"), "RU": ("nameparser.locales.ru", "RU"), "SK": ("nameparser.locales.sk", "SK"), "SL": ("nameparser.locales.sl", "SL"), diff --git a/nameparser/locales/_pt_given_names.py b/nameparser/locales/_pt_given_names.py new file mode 100644 index 000000000..6752aad8a --- /dev/null +++ b/nameparser/locales/_pt_given_names.py @@ -0,0 +1,129 @@ +"""Portuguese given names for rules/O6's veto (#1453): a word only a +given name is, which ``two_family_names`` leaves where it stands, so +"Ana Beatriz Costa" keeps family "Costa". locales.PT_BR and +locales.PT_PT carry it as their lexicon fragment, +``Lexicon(given_names=GIVEN_NAMES)``, and turn ``two_family_names`` +on; locales.PT, chosen by language, carries neither (decisions/O6, +2026-11-19). + +Data source: ORCID's public data file of October 2025 (CC0, +https://info.orcid.org/documentation/integration-guide/working-with-bulk-data/), +each holder's given-names and family-name boxes and the country they +work or live in. This module is derived from them: the project's own +measurement, credited here (CC0 asks for no credit, so README.rst's +License section, which lists the sources whose licences ask for it, +does not name it). The words of at least +five uses in the boxes of researchers in Portugal and Brazil, records +past the first 3,000 of each country, at least 70% of whose uses are +in the given box, ranked by given uses, written lower-cased without +accents but with ç, as ``Lexicon.given_names`` matches them +(``given_name_key``); and, after them, each word written with ç again +with c, where that spelling passes the same share over every use it +stands for, since data without the letter writes "Goncalo" for +Gonçalo. Every word was read by hand before the list shipped. +tools/pt_given_names.py derives the block below, with the cutoff and +share it states; do not edit it by hand. A change to the list is a +change to the cutoff, decided against the per-country measurement in +decisions/O6. +""" +from __future__ import annotations + +# -- BEGIN generated by tools/pt_given_names.py; edit the tool, not this block -- +_RANKED = ( + "maria", "ana", "joao", "jose", "pedro", "luis", "carlos", "antonio", + "paulo", "miguel", "cristina", "beatriz", "paula", "joana", "mariana", "ines", + "carolina", "ricardo", "isabel", "sofia", "andre", "manuel", "catarina", "rita", + "patricia", "daniel", "fernando", "henrique", "bruno", "francisco", "jorge", "tiago", + "lucas", "nuno", "rui", "gabriel", "filipe", "carla", "eduardo", "fernanda", + "margarida", "alexandre", "sara", "raquel", "claudia", "filipa", "rafael", "guilherme", + "luiz", "daniela", "gabriela", "diogo", "teresa", "vitor", "marta", "bruna", + "helena", "juliana", "rodrigo", "felipe", "julia", "vinicius", "alexandra", "susana", + "andreia", "barbara", "jessica", "sandra", "gustavo", "luisa", "camila", "fabio", + "laura", "victor", "vanessa", "marcelo", "sergio", "augusto", "marcos", "eduarda", + "hugo", "luiza", "leticia", "clara", "david", "diana", "caroline", "amanda", + "mario", "sonia", "leonardo", "matheus", "natalia", "flavia", "fatima", "marco", + "monica", "aline", "thiago", "gonçalo", "vitoria", "marina", "larissa", "roberto", + "alberto", "adriana", "rafaela", "manuela", "renata", "cesar", "regina", "silvia", + "francisca", "luciana", "catia", "renato", "tania", "debora", "lucia", "leandro", + "marcia", "angela", "lara", "anna", "isabela", "mafalda", "aparecida", "andrea", + "leonor", "luana", "thais", "liliana", "marcio", "diego", "joaquim", "alice", + "priscila", "rogerio", "tatiana", "alessandra", "cecilia", "vera", "arthur", "isabella", + "marisa", "igor", "tomas", "livia", "bianca", "elisabete", "frederico", "giovanna", + "simone", "adriano", "julio", "ruben", "anderson", "samuel", "elsa", "helder", + "madalena", "andressa", "cristiane", "flavio", "nelson", "sarah", "celia", "claudio", + "fabiana", "veronica", "anabela", "ligia", "lorena", "victoria", "danielle", "mara", + "marcela", "roberta", "alex", "elisa", "marilia", "valeria", "vania", "viviane", + "soraia", "artur", "sabrina", "cristiana", "elaine", "luciano", "angelo", "douglas", + "giovana", "milena", "rebeca", "rute", "daniele", "emanuel", "erika", "ingrid", + "lais", "antonia", "carina", "denise", "nathalia", "eliane", "fabricio", "katia", + "matilde", "caio", "erica", "karina", "mayara", "nayara", "renan", "tatiane", + "amelia", "ellen", "gabriella", "gabrielle", "heloisa", "isadora", "jefferson", "karen", + "marcus", "nadia", "vasco", "brenda", "carmen", "danilo", "ester", "filomena", + "kelly", "alvaro", "elizabeth", "ivo", "jaqueline", "juan", "juliano", "yasmin", + "alan", "armando", "michele", "monique", "raphael", "alfredo", "angelica", "cintia", + "davi", "emilia", "fabiola", "luan", "nicole", "raissa", "robson", "ronaldo", + "samara", "valter", "wilson", "yuri", "cristiano", "daiane", "deborah", "geraldo", + "gisele", "janaina", "karla", "lilian", "magda", "telmo", "wagner", "breno", + "cassia", "edson", "eugenia", "eva", "gilberto", "ivan", "jaime", "lidia", + "michelle", "murilo", "nicolas", "olga", "paola", "raul", "rosana", "suelen", + "telma", "virginia", "william", "eliana", "fabiano", "jean", "jeferson", "manoel", + "marlene", "mauro", "melissa", "micaela", "orlando", "oscar", "ramon", "suzana", + "alessandro", "candida", "cristine", "giulia", "karine", "lurdes", "maira", "pablo", + "pamela", "patrick", "rodolfo", "sandro", "silvana", "talita", "vanda", "emilly", + "gabriele", "jonathan", "joyce", "mariane", "martim", "paloma", "tamires", "ariane", + "aurelio", "dulce", "edgar", "edna", "iolanda", "juliane", "lia", "micael", + "michael", "otavio", "richard", "vivian", "adriane", "alda", "allan", "americo", + "celso", "christian", "evandro", "heitor", "irene", "izabel", "liliane", "luciane", + "miriam", "moises", "nathan", "rubens", "sophia", "stephanie", "willian", "alexander", + "cynthia", "daniella", "dayane", "dina", "emily", "iara", "iris", "isabelle", + "italo", "joel", "leila", "marcella", "milene", "natacha", "saulo", "tamara", + "thalita", "wellington", "constança", "evelyn", "glaucia", "hellen", "icaro", "james", + "jennifer", "jonas", "jussara", "leonel", "lourdes", "osvaldo", "silvio", "socorro", + "adelino", "alexia", "alisson", "anibal", "augusta", "carlota", "ceu", "cibele", + "elisabeth", "emerson", "enrique", "eugenio", "gilson", "gisela", "giselle", "gloria", + "israel", "luzia", "maiara", "marlon", "priscilla", "rayssa", "reginaldo", "selma", + "suellen", "tulio", "adelaide", "alana", "allana", "andreza", "anne", "ariel", + "arnaldo", "camilla", "christine", "dora", "eder", "elisangela", "ema", "emanuelle", + "erick", "estela", "everton", "fabiane", "francielle", "gabrielly", "george", "graziela", + "helia", "helio", "isis", "izabela", "kleber", "luciene", "lucilia", "magno", + "maisa", "marcel", "marcelle", "raphaela", "roger", "romulo", "salome", "samira", + "sandrina", "sheila", "stella", "tereza", "terezinha", "thaina", "abel", "agnes", + "aida", "ariana", "celina", "cleber", "cristian", "dario", "elena", "eunice", + "ezequiel", "franciele", "geovana", "humberto", "irina", "isa", "isaac", "jacqueline", + "jade", "joseane", "josiane", "karoline", "liana", "lilia", "lisandra", "manoela", + "michel", "mirian", "olinda", "olivia", "regiane", "robert", "rosane", "samanta", + "savio", "solange", "soraya", "taina", "thales", "wesley", "yara", "yasmim", + "adolfo", "alicia", "andrei", "andrey", "anselmo", "anthony", "arlindo", "aurora", + "carine", "christina", "cidalia", "clarice", "clarissa", "cleide", "cristovao", "davide", + "denis", "elvira", "emilio", "enzo", "esmeralda", "estefania", "eurico", "francesca", + "gabrieli", "georgia", "gessica", "giovane", "giovani", "graziele", "iago", "jackson", + "jonatas", "karolina", "keila", "lavinia", "ludmila", "maristela", "mary", "mercia", + "millena", "nelia", "rafaella", "rayanne", "ronald", "rosalia", "samantha", "saul", + "sueli", "tayna", "thamires", "thayna", "thays", "thomas", "valentina", "viviana", + "adrielle", "alceu", "andres", "angel", "arlete", "charles", "christiane", "christopher", + "cinthia", "clarisse", "dalila", "damaris", "dayana", "deise", "edilson", "elton", + "emanuele", "everaldo", "fabricia", "francine", "gerson", "giovanni", "helga", "isabele", + "ismael", "ivone", "izabella", "john", "josue", "licinio", "luma", "mariangela", + "melanie", "mohamed", "mohammad", "neuza", "peter", "pilar", "rachel", "rayane", + "samir", "sidney", "stefanie", "stephany", "tais", "valdir", "vanderlei", "virgilio", + "yan", "adalberto", "adelia", "agata", "ailton", "alison", "ane", "anelise", + "antony", "armindo", "beatrice", "bosco", "celeste", "chiara", "cibelle", "cicero", + "dandara", "danielly", "dayse", "denize", "edite", "edmundo", "elen", "eliza", + "emmanuel", "eric", "esther", "euler", "ewerton", "fellipe", "francesco", "geovanna", + "giancarlo", "gilmar", "gislene", "giuseppe", "glauco", "gleice", "glenda", "goreti", + "herminia", "higor", "ian", "iasmin", "ilda", "isabelly", "ivonete", "izadora", + "jair", "javier", "jeane", "jeremias", "jhonatan", "joelma", "junio", "kassia", + "kevin", "laryssa", "laysa", "lenia", "liane", "louise", "luca", "marie", + "martha", "maryana", "max", "mirella", "monalisa", "morgana", "naiara", "naira", + "nara", "natali", "nataly", "nazare", "neide", "nicolle", "nilson", "noemi", + "otilia", "philippe", "plinio", "rebecca", "romeu", "rosangela", "roseli", "rosemary", + "ruan", "rubia", "ruth", "sayuri", "sylvia", "tassia", "thayse", "vilma", + "wendell", "wendy", "belem", "cassio", "delfim", "dolores", "florence", "jamile", + "jamille", "jane", "jordan", "kellen", "muhammad", "stefano", "tobias", +) +_C_SPELLINGS = ( + "goncalo", "constanca", +) +# -- END generated -- + +GIVEN_NAMES = frozenset(_RANKED + _C_SPELLINGS) diff --git a/nameparser/locales/pt.py b/nameparser/locales/pt.py index 07499da4f..ef7ac334d 100644 --- a/nameparser/locales/pt.py +++ b/nameparser/locales/pt.py @@ -9,8 +9,9 @@ generation behind, as the default reads it (decisions/vocabulary-model, the 2026-10-30 phase 3g entry); its academic titles (``Doutor``, ``Professora``) are read by default since #1115. locales.PT_BR -chooses ``pt-BR``, which selects ``pt`` too, so it reads all of these -the same way. +and locales.PT_PT choose ``pt-BR`` and ``pt-PT``, which select ``pt`` +too, so they read all of these the same way; each also reads two +family names, which this pack does not (decisions/O6, 2026-11-19). Data sources: the counts are on the readings in pt.toml (tools/name_usage.py and the local corpora). The pack carries no diff --git a/nameparser/locales/pt_br.py b/nameparser/locales/pt_br.py index 009c47f62..78016bbc3 100644 --- a/nameparser/locales/pt_br.py +++ b/nameparser/locales/pt_br.py @@ -1,8 +1,8 @@ -"""The Brazilian Portuguese locale pack: vocabulary-only -- it chooses -the language ``pt-BR``, which selects nameparser/vocab/pt-BR.toml and -its ancestor pt.toml, and turns on the agnomen reading pt-BR.toml -writes ``default = false``: ``SB``, Sobrinho abbreviated as Brazilian -filings write it, which outside Brazil is the S.B. degree +"""The Brazilian Portuguese locale pack. It chooses the language +``pt-BR``, which selects nameparser/vocab/pt-BR.toml and its ancestor +pt.toml, and turns on the agnomen reading pt-BR.toml writes +``default = false``: ``SB``, Sobrinho abbreviated as Brazilian filings +write it, which outside Brazil is the S.B. degree (decisions/vocabulary-model, the 2026-10-30 phase 3h entry). It is then gated by the count as ``sobrinho`` is (rules/S11): ``JOSE CARLOS SILVA SB`` gives suffix ``SB`` where the default gives family ``SB``. The @@ -14,24 +14,44 @@ as locales.PT does; pt's titles (``Doutor``, ``Professora``) are read by default since #1115. +It reads two family names (``Policy.two_family_names``, rules/O6), its +policy patch compiled from pt-BR.toml's [rules] table by +tools/vocab/build.py: ``Ana Souza Lima`` gives family ``Souza Lima``. +And it carries the Portuguese given-name list as its lexicon fragment, +``Lexicon(given_names=...)``, which keeps a given name out of the +family: ``Ana Beatriz Costa`` keeps family ``Costa``. locales.PT, the +pack chosen by language, turns neither on, since Angolan and +Mozambican names lose under the switch (decisions/O6, the 2026-11-19 +entry). + Data sources: tse-donors, Brazilian candidates' receipts as filed beside the registry's spelling (tools/differential/local_tse.py); the counts -are on the readings in pt-BR.toml. The pack carries no lexicon fragment -and no policy patch. +are on the readings in pt-BR.toml. The given names are +nameparser/locales/_pt_given_names.py's, measured on ORCID's public +data file (CC0), whose docstring credits it. -Declared deviations (mechanisms.md#LOCALE-PACKS-PURE-DATA): a -vocabulary pack's deviations are derived, not declared -- the words -whose compiled readings its choice changes -(``_reading_index.changed_words``), which the non-interference gate in -tests/v2/test_locales.py reads -- so this module defines no DEVIATES. +Declared deviations (mechanisms.md#LOCALE-PACKS-PURE-DATA): the choice's +are derived, not declared -- the words whose compiled readings it +changes (``_reading_index.changed_words``), which the non-interference +gate in tests/v2/test_locales.py ors in -- and the patch and the +fragment act only where rules/O6 does, so DEVIATES is rules/O6's +declaration. """ from __future__ import annotations from nameparser._lexicon import Lexicon -from nameparser._locale import Locale +from nameparser._locale import Locale, deviates_by_two_family_names, rules_patch +from nameparser.locales._pt_given_names import GIVEN_NAMES PT_BR = Locale( code="pt_br", - lexicon=Lexicon.empty(), + lexicon=Lexicon(given_names=GIVEN_NAMES), + # nameparser/vocab/pt-BR.toml's [rules], the country's own: pt.toml, + # the language's, holds none (decisions/O6, 2026-11-19) + policy=rules_patch("pt-BR"), languages=frozenset({"pt-BR"}), ) + + +# rules/O6's declaration, which every pack turning O6 on shares +DEVIATES = deviates_by_two_family_names diff --git a/nameparser/locales/pt_pt.py b/nameparser/locales/pt_pt.py new file mode 100644 index 000000000..6bae6f7ba --- /dev/null +++ b/nameparser/locales/pt_pt.py @@ -0,0 +1,43 @@ +"""The European Portuguese locale pack: locales.PT for names from +Portugal, with two family names. It chooses ``pt-PT``, which selects +its ancestor pt.toml (nameparser/vocab/pt-PT.toml holds only the +[rules] table ``rules_patch`` reads, and no reading for a choice to +select), so it reads every word locales.PT reads +(``do`` a particle, ``da Piedade`` the second half of a compound given +name); it reads two family names (``Policy.two_family_names``, +rules/O6), its policy patch compiled from pt-PT.toml's [rules] table +by tools/vocab/build.py: ``Rui Sousa Pinto`` gives family ``Sousa +Pinto``, where locales.PT gives middle ``Sousa``; and it carries +nameparser/locales/_pt_given_names.py as its lexicon fragment, the +list locales.PT_BR carries, which keeps a given name out of the family: +``Ana Beatriz Costa`` keeps family ``Costa``. Cape Verdean and São +Toméan names read better under it than under locales.PT, Angolan and +Mozambican names worse (decisions/O6, the 2026-11-19 entry, which +measures it). + +Data sources: the counts are on the readings in pt.toml; the given +names are measured on ORCID's public data file (CC0), whose credit the +list's module carries. + +Declared deviations (mechanisms.md#LOCALE-PACKS-PURE-DATA): the choice's +are derived, as locales.PT's are, and the patch and the fragment act +only where rules/O6 does, so DEVIATES is rules/O6's declaration. +""" +from __future__ import annotations + +from nameparser._lexicon import Lexicon +from nameparser._locale import Locale, deviates_by_two_family_names, rules_patch +from nameparser.locales._pt_given_names import GIVEN_NAMES + +PT_PT = Locale( + code="pt_pt", + lexicon=Lexicon(given_names=GIVEN_NAMES), + # nameparser/vocab/pt-PT.toml's [rules], the country's own: pt.toml, + # the language's, holds none (decisions/O6, 2026-11-19) + policy=rules_patch("pt-PT"), + languages=frozenset({"pt-PT"}), +) + + +# rules/O6's declaration, which every pack turning O6 on shares +DEVIATES = deviates_by_two_family_names diff --git a/nameparser/vocab/README.md b/nameparser/vocab/README.md index 969e6546c..a714ad7f4 100644 --- a/nameparser/vocab/README.md +++ b/nameparser/vocab/README.md @@ -295,7 +295,7 @@ patronymic_rules = ["east-slavic"] | `two_given_names` | `true` | `two_given_names` (rules/O7) | | `initials_as_family` | `true` | `initials_as_family` (rules/O8) | -A rule is written only to turn it on: `name_order = "given-first"`, `two_family_names = false`, `two_given_names = false` and `initials_as_family = false` are the defaults, and a pack's value overrides the caller's own, so the build refuses all four rather than let a pack switch a caller's rule off. The files that hold a table are exactly the ones `PACK_RULES` in `tools/vocab/build.py` lists, each beside the pack that reads it (`tr.toml` is `locales.TR_AZ`'s, one file for Turkish and Azerbaijani, since there is no `az.toml`; `es.toml`'s is `locales.ES_AR`'s too, a country pack reading its language's table, since none of the countries measured turns a rule differently from its language); a table in any other file is a build error, since nothing would read it, and so is a file listed there without one. Writing a `[rules]` table does not choose the file's vocabulary: that is the pack's `languages`, a separate field. +A rule is written only to turn it on: `name_order = "given-first"`, `two_family_names = false`, `two_given_names = false` and `initials_as_family = false` are the defaults, and a pack's value overrides the caller's own, so the build refuses all four rather than let a pack switch a caller's rule off. The files that hold a table are exactly the ones `PACK_RULES` in `tools/vocab/build.py` lists, each beside the pack that reads it (`tr.toml` is `locales.TR_AZ`'s, one file for Turkish and Azerbaijani, since there is no `az.toml`; `es.toml`'s is `locales.ES_AR`'s too, a country pack reading its language's table; and `pt-BR.toml`'s and `pt-PT.toml`'s are `locales.PT_BR`'s and `locales.PT_PT`'s, countries turning on a rule `pt.toml` leaves off, `pt-PT.toml` holding the table and no word); a table in any other file is a build error, since nothing would read it, and so is a file listed there without one. Writing a `[rules]` table does not choose the file's vocabulary: that is the pack's `languages`, a separate field. A rule KIND the table does not list (a married-name ending) is a change to the parser, not to a file: a new `Policy` field (with `ADDED_IN`), a row in `build.py`'s `RULE_KEYS` and in `_locale.py`'s `_RULE_VALUES`, and a mechanisms.md entry of its own for the rule kind, or an amendment to the entry whose shape it shares (`initials_as_family` joined DECLARED-SPAN's switches) (mechanisms.md#LOCALE-PACKS-PURE-DATA). `tests/v2/test_vocab.py` holds the two tables to each other and to `Policy`. diff --git a/nameparser/vocab/pt-BR.toml b/nameparser/vocab/pt-BR.toml index 8e1b0507b..0ea1745e9 100644 --- a/nameparser/vocab/pt-BR.toml +++ b/nameparser/vocab/pt-BR.toml @@ -1,5 +1,12 @@ schema = 1 +# locales.PT_BR reads its names with two family names (rules/O6), its given-name +# list keeping a given name out of the family; pt.toml, which locales.PT reads +# for Portuguese names from any country, holds no table (decisions/O6, the +# 2026-11-19 entry) +[rules] +two_family_names = true + [[word]] text = "f" excluded = { agnomen = { reason = "Filho written short in 15 tse-donors filed/registry pairs (2026-10-25), but written exactly as an initial is, and in those filings mostly one: turned on by a Brazilian Portuguese choice it moved 152 tse-donors filed/registry pairs (measured with 'n' on too, a pair holding both counted under the letter its reading took first) that the choice of Portuguese alone does not, and in 104 of them the registry spells a surname the letter abbreviates (ANA MARIA F, registry ANA MARIA FILGUEIRAS) where in 48 it spells FILHO (2026-10-30). No writing tells the two apart, so no pack reads it", issue = [843, 753], decided = 2026-10-30 } } diff --git a/nameparser/vocab/pt-PT.toml b/nameparser/vocab/pt-PT.toml new file mode 100644 index 000000000..a89f0b648 --- /dev/null +++ b/nameparser/vocab/pt-PT.toml @@ -0,0 +1,9 @@ +schema = 1 + +# European Portuguese: locales.PT_PT reads its names with two family names +# (rules/O6), its given-name list keeping a given name out of the family. +# The file holds no word: a reading Portugal writes and Brazil does not +# has not been needed, and pt.toml holds the language's (decisions/O6, the +# 2026-11-19 entry) +[rules] +two_family_names = true diff --git a/tests/v2/cases.py b/tests/v2/cases.py index 47572fb59..26bc6cdfb 100644 --- a/tests/v2/cases.py +++ b/tests/v2/cases.py @@ -17972,6 +17972,53 @@ def _check_cjk_shape_purity(self) -> None: "so the " "pack reads it as a first family name, as locales.ES does; " "read middle 'Emerita' 3.0.0 through 3.1"), + Case("two_family_names_under_pt_br", "Ana Souza Lima", + {"given": "Ana", "family": "Souza Lima"}, + locale="pt_br", classification="feat(#1453)", + notes="O6, pt-BR.toml's [rules]; read middle 'Souza' 3.0.0 " + "through 3.1"), + Case("two_family_names_under_pt_br_in_capitals", "ANA SOUZA LIMA", + {"given": "ANA", "family": "SOUZA LIMA"}, + locale="pt_br", classification="feat(#1453)", + notes="O6 reads no case; read middle 'SOUZA' 3.0.0 through 3.1"), + Case("two_family_names_under_pt_pt", "Rui Sousa Pinto", + {"given": "Rui", "family": "Sousa Pinto"}, + locale="pt_pt", classification="feat(#1453)", + notes="O6, pt-PT.toml's [rules]; locales.PT_PT is new in 3.2"), + Case("no_two_family_names_under_pt", "Rui Sousa Pinto", + {"given": "Rui", "middle": "Sousa", "family": "Pinto"}, + locale="pt", classification="parity", + notes="the pack chosen by language leaves O6 off: pt.toml holds " + "no [rules] table (decisions/O6, 2026-11-19)"), + Case("listed_portuguese_given_name_under_pt_br", "Ana Beatriz Costa", + {"given": "Ana", "middle": "Beatriz", "family": "Costa"}, + locale="pt_br", classification="parity", + notes="O6: 'beatriz' is in the Portuguese given-name list, so " + "the switch leaves it where it stands"), + Case("c_spelling_of_a_listed_given_name_under_pt_pt", "Pedro Goncalo Matos", + {"given": "Pedro", "middle": "Goncalo", "family": "Matos"}, + locale="pt_pt", classification="parity", + notes="O6: Gonçalo is listed with its ç and again with c, as data " + "without the letter writes it"), + Case("agnomen_behind_two_family_names_under_pt_br", "Pedro Alves Lima Filho", + {"given": "Pedro", "family": "Alves Lima", "suffix": "Filho"}, + locale="pt_br", classification="feat(#1453)", + ambiguities=("suffix-or-name",), + notes="S11 peels the agnomen, then O6 takes 'Alves'; read middle " + "'Alves', family 'Lima' 3.0.0 through 3.1"), + Case("particle_family_under_pt_br", "Joao Pedro da Silva Santos", + {"given": "Joao", "middle": "Pedro", "family": "da Silva Santos"}, + locale="pt_br", classification="parity", + notes="O6: the family already counts two names ('da Silva', " + "'Santos'), so the switch takes nothing"), + Case("three_family_names_read_as_two_under_pt_br", + "Leonardo Mirandela Gomes Paz", + {"given": "Leonardo", "middle": "Mirandela", "family": "Gomes Paz"}, + locale="pt_br", classification="feat(#1453)", + notes="O6 takes one word, so a family of three surnames keeps its " + "first as a middle name, a gap #1453 leaves for #1482; " + "read middle 'Mirandela Gomes', family 'Paz' 3.0.0 " + "through 3.1"), Case("given_name_title_marquis_at_the_head", "Marquis Johnson", {"given": "Marquis", "family": "Johnson"}, classification="fix(#913)", diff --git a/tests/v2/test_cli.py b/tests/v2/test_cli.py index 64826a62e..521dcf6b3 100644 --- a/tests/v2/test_cli.py +++ b/tests/v2/test_cli.py @@ -505,7 +505,7 @@ def test_cli_strict_with_a_pack_whose_code_is_no_language( @pytest.mark.parametrize("tag,pack", [ # a bare choice would drop the pack's segmentation, two family # names and given-name list, and the segmenter, in silence - ("zh-CN", "zh"), ("es-MX", "es"), ("ja-JP", "ja"), ("pt-PT", "pt"), + ("zh-CN", "zh"), ("es-MX", "es"), ("ja-JP", "ja"), ("pt-AO", "pt"), # a script subtag is not a region, and the message says neither ("zh-Hant", "zh"), ]) @@ -521,3 +521,11 @@ def test_cli_a_tag_spelled_for_a_packs_code_is_that_pack( assert (_fields(capsys, "--locale", tag, "Pedro Silva Sb") == _fields(capsys, "--locale", "pt_br", "Pedro Silva Sb")) assert _fields(capsys, "--locale", tag, "Pedro Silva Sb")["suffix"] == "Sb" + + +@pytest.mark.parametrize("tag", ["pt-PT", "pt_pt", "PT-PT"]) +def test_cli_the_portugal_pack_is_named_by_its_tag( + capsys: pytest.CaptureFixture[str], tag: str) -> None: + # pt_pt reads two family names where pt, the language's pack, does not + assert _fields(capsys, "--locale", tag, "Rui Sousa Pinto")["family"] == "Sousa Pinto" + assert _fields(capsys, "--locale", "pt", "Rui Sousa Pinto")["family"] == "Pinto" diff --git a/tests/v2/test_config_diff.py b/tests/v2/test_config_diff.py index 772f2ea33..0f9c6df59 100644 --- a/tests/v2/test_config_diff.py +++ b/tests/v2/test_config_diff.py @@ -319,14 +319,15 @@ def test_every_shipped_pack_rides_on_some_tag() -> None: from nameparser._reading_index import selected reached = {item.lower() for tag in cd.choosable() for spec in cd.gap_specs(tag) for item in spec.partition(":")[2].split("+") if item.isupper()} - # a pack choosing a region tag no file holds (es_ar's es-AR) selects - # its language's files and nothing more, so the strict gap the report - # measures for the pack choosing those files is its own + # a pack choosing a region tag no file holds (es_ar's es-AR), or one + # whose file holds no reading (pt_pt's pt-PT, a [rules] table alone), + # selects its language's files and nothing more, so the strict gap + # the report measures for the pack choosing those files is its own files = {code: selected(locales.get(code).languages) for code in locales.available() if locales.get(code).languages} same_files = {code for code, f in files.items() if any(f == files.get(other) for other in reached - {code})} - assert same_files == {"es_ar"} + assert same_files == {"es_ar", "pt", "pt_pt"} assert set(locales.available()) <= reached | same_files @@ -334,6 +335,9 @@ def test_a_pack_choosing_no_language_is_stacked_with_its_tag() -> None: assert cd.gap_specs("zh") == ("plain:ZH+zh", "strict:ZH+zh") assert cd.gap_specs("tr") == ("plain:TR_AZ+tr", "strict:TR_AZ+tr") assert cd.gap_specs("pt-BR") == ("plain:PT_BR", "strict:PT_BR") + # pt-PT.toml holds a [rules] table and no reading: a plain choice of + # the tag selects pt.toml, so its plain side is the pack, not the default + assert cd.gap_specs("pt-PT") == ("plain:PT_PT", "strict:PT_PT") assert cd.gap_specs("vi") == ("plain:VI", "strict:VI") # hu.toml holds no reading a parse reads, only exclusions, so the # plain side is the default, never an inert plain choice of the tag diff --git a/tests/v2/test_familiar_tool.py b/tests/v2/test_familiar_tool.py index 59a52d3b8..9f483ce35 100644 --- a/tests/v2/test_familiar_tool.py +++ b/tests/v2/test_familiar_tool.py @@ -114,7 +114,7 @@ def test_every_shipped_reading_is_one_the_tool_writes() -> None: # familiar and spelling reading is the reviewed file's by_kind: dict[str, list[tuple[str, str]]] = {k: [] for k in tool.KINDS} for path in sorted(_VOCAB.glob("*.toml")): - for e in tomllib.loads(path.read_text())["word"]: + for e in tomllib.loads(path.read_text()).get("word", []): for kind in tool.KINDS: if kind in e: by_kind[kind].append((path.name, e[kind]["note"])) diff --git a/tests/v2/test_layering.py b/tests/v2/test_layering.py index b802ec081..3082845fe 100644 --- a/tests/v2/test_layering.py +++ b/tests/v2/test_layering.py @@ -247,7 +247,10 @@ def _locale_rules() -> dict[str, tuple[str, ...]]: A pack (`es.py`) may import _LOCALE_PACK_ALLOWED and its own private data modules: `_es_given_names.py` belongs to `es.py`, the pack with the LONGEST stem the data module's name opens with, so - `_es_ar_given_names.py` is `es_ar.py`'s and not `es.py`'s. A data + `_es_ar_given_names.py` is `es_ar.py`'s and not `es.py`'s; and a + data module belongs to its pack's country packs too, a stem of the + pack's own and a region (`_pt_given_names.py` to `pt_br.py` and + `pt_pt.py`, which share one list, decisions/O6 2026-11-19). A data module (a leading underscore, rules/O6's given-name lists, #959) imports nothing internal.""" locales_dir = pathlib.Path(nameparser.locales.__file__).parent @@ -261,12 +264,12 @@ def _locale_rules() -> dict[str, tuple[str, ...]]: if stem.startswith("_"): rules[f"locales/{path.name}"] = () continue + owners = {data.stem: max((s for s in stems if data.stem.startswith(f"_{s}_")), + key=len, default=None) + for data in locales_dir.glob("_*.py") if data.stem != "__init__"} own = tuple( - f"nameparser.locales.{data.stem}" - for data in sorted(locales_dir.glob("_*.py")) - if data.stem != "__init__" - and max((s for s in stems if data.stem.startswith(f"_{s}_")), - key=len, default=None) == stem) + f"nameparser.locales.{data}" for data, owner in sorted(owners.items()) + if owner is not None and (stem == owner or stem.startswith(f"{owner}_"))) rules[f"locales/{path.name}"] = _LOCALE_PACK_ALLOWED + own return rules @@ -296,6 +299,11 @@ def test_layering_contract() -> None: # a data module is its longest-stemmed pack's alone ("es", "_es_ar_given_names", False), ("pt", "_es_given_names", False), + # and its pack's country packs', which may share one list + ("pt_br", "_pt_given_names", True), + ("pt_pt", "_pt_given_names", True), + ("es_ar", "_es_given_names", True), + ("pt_br", "_es_given_names", False), ]) def test_a_pack_may_import_its_own_data_module_only( pack: str, data: str, allowed: bool) -> None: @@ -388,7 +396,11 @@ def test_every_locales_module_is_checked() -> None: assert rule == (), name else: assert rule[:len(_LOCALE_PACK_ALLOWED)] == _LOCALE_PACK_ALLOWED - assert all(extra.startswith(f"nameparser.locales._{name}_") + # its own data modules, and its language pack's (es_ar's + # and pt_br's: a stem of the language's and a region) + stems = {name, name.rsplit("_", 1)[0]} + assert all(any(extra.startswith(f"nameparser.locales._{stem}_") + for stem in stems) for extra in rule[len(_LOCALE_PACK_ALLOWED):]), name @@ -903,13 +915,15 @@ def test_the_check_finds_a_tool_read_through_an_alias( #: `sets =` binding and the two suffix sets it reads (the given names #: refusing a listed suffix, #1357), 25 -> 28 (`listed_titles` #: reading `title_abbreviations` too adds none, that set being no -#: field of `_VOCAB_FIELDS`). 4i-a's own count was 114 (on +#: field of `_VOCAB_FIELDS`); and tools/pt_given_names.py reading the +#: default's particles, a family word after one not counted (#1453), +#: 28 -> 29. 4i-a's own count was 114 (on #: that tree's sources), two of them `getattr`s in #: `_parser._apply_choice`, which read the sets through #: `_lexicon._fields_of` from 4i-b until 4i-c retired it. #: A reader added through `_sets` moves these, and they are re-taken #: then: they count what the check would refuse with the move undone. -_UNGUARDED_READS = {"library": 198, "tools": 28} +_UNGUARDED_READS = {"library": 198, "tools": 29} def test_the_check_refuses_every_read_4i_a_moved() -> None: diff --git a/tests/v2/test_locales.py b/tests/v2/test_locales.py index 182f4ffd4..716038747 100644 --- a/tests/v2/test_locales.py +++ b/tests/v2/test_locales.py @@ -119,10 +119,10 @@ def test_locales_get_and_available() -> None: assert locales.get("ru") is locales.RU assert set(locales.available()) == { "ar", "bn", "cs", "es", "es_ar", "ga", "gd", "he", "hi", "hr", "ja", "mn", - "my", "ne", "nl", "pt", "pt_br", "ru", "sk", "sl", "tr_az", "vi", "zh"} + "my", "ne", "nl", "pt", "pt_br", "pt_pt", "ru", "sk", "sl", "tr_az", "vi", "zh"} with pytest.raises( KeyError, - match="ar, bn, cs, es, es_ar, ga, gd, he, hi, hr, ja, mn, my, ne, nl, pt, pt_br, ru, sk, sl, tr_az, vi, zh"): + match="ar, bn, cs, es, es_ar, ga, gd, he, hi, hr, ja, mn, my, ne, nl, pt, pt_br, pt_pt, ru, sk, sl, tr_az, vi, zh"): locales.get("xx") # the segmenter FACTORY is not a locale: it is an ordinary function # on the package, so it must not appear among the codes @@ -442,7 +442,7 @@ def test_a_strict_portuguese_choice_reads_the_given_names_es_also_marks( # reading no es.toml keeps the default's middle name; the others # (carmen, pilar, rosario, ...) it leaves to the family assert parse(text).middle == middle - for pack in (locales.PT, locales.PT_BR): + for pack in (locales.PT, locales.PT_BR, locales.PT_PT): assert parser_for(pack, strict=True).parse(text).middle == middle, pack @@ -469,7 +469,7 @@ def test_es_and_pt_pack_contents() -> None: # sr keeps es's and pt's generation beside the salutation, so the # choice leaves it a dual position decides, as the default reads it for packed in (_require_packed("es"), _require_packed("pt"), - _require_packed("pt_br")): + _require_packed("pt_br"), _require_packed("pt_pt")): for text in ("Gary Holloway Sr", "Sr. Juan Pérez", "J. Smith Sr."): assert packed.parse(text).as_dict() == parse(text).as_dict() # the patch's and the fragment's declaration: rules/O6's three name @@ -1102,7 +1102,7 @@ def test_the_twice_counted_controls_each_move_a_row() -> None: @pytest.mark.parametrize("name", _NARROWED) -@pytest.mark.parametrize("code", ["es", "es_ar", "cs", "sk"]) +@pytest.mark.parametrize("code", ["es", "es_ar", "cs", "sk", "pt_br", "pt_pt"]) def test_a_name_the_declaration_stopped_counting_twice_reads_as_the_default( code: str, name: str) -> None: assert _require_packed(code).parse(name).as_dict() == _default_parse(name) @@ -2396,14 +2396,27 @@ def test_a_choice_word_rotator_is_moved_by_the_choice_alone(code: str) -> None: "John Smith DO", # do, pt's particle, not DO "ANA SILVA E SOUZA", # e, pt's connective ] +# pt_br and pt_pt: the patch's rules/O6, as es's rows hold it, beside +# their choices' words; the list's own words read as the default does, +# so they are no rotators (held in the contents test) +_PT_TWO_FAMILY_NAMES = [ + "Rui Sousa Pinto", # rules/O6, the patch + "Ana Beatriz Souza Lima", # rules/O6 behind a two-word given part + "김민준 1", # rules/O6 over a segmented name and a word of no letter + "Jan\u200bPavel -", # rules/O6 over a zero-width split and a lone mark +] _ROTATORS["pt_br"] = [ - "JOSE CARLOS SILVA SB", # sb - "Jose Carlos Silva Sb.", # sb, dotted - "JOSE SILVA SB", # sb, one word to spare + # sb behind listed given names, which the patch and the list alone + # leave as the default reads them (rules/O6's veto) + "JOSE CARLOS PEDRO SB", # sb + "Jose Carlos Pedro Sb.", # sb, dotted + "JOSE CARLOS SB", # sb, one word to spare *_PT_PARTICLE_GIVEN, # pt's given names P10 completes "John Smith DO", # do, pt's particle, not DO "ANA SILVA E SOUZA", # e, pt's connective + *_PT_TWO_FAMILY_NAMES, ] +_ROTATORS["pt_pt"] = [*_ROTATORS["pt"], *_PT_TWO_FAMILY_NAMES] # #1115 turned these titles on by default, so no choice moves them: the @@ -2470,6 +2483,12 @@ def test_a_choice_word_rotator_is_moved_by_the_choice_alone(code: str) -> None: "Professora Rosária Lima", # professora, pt's title "Profa Maria Souza", # profa, pt's title ], + "pt_pt": [ + "Doutor João Silva", # doutor, pt's title + "Fernanda Lucchese, Doutora", # doutora, pt's title + "Professora Rosária Lima", # professora, pt's title + "Profa Maria Souza", # profa, pt's title + ], } @@ -3137,11 +3156,12 @@ def test_the_west_and_south_slavic_packs_repair_their_titles_case() -> None: ("S.", "B.", "John Smith", "", ("SUFFIX_OR_NAME",)), ("S.", "B.", "John Smith", "", ("SUFFIX_OR_NAME",))), # F and N, written as an initial is, are excluded, the pack included - # (pt-BR.toml): the family name they spell, by default and under it + # (pt-BR.toml): the family name they spell, by default and under it, + # where the pack's two family names (rules/O6) take the word before ("PT_BR", "JOSE CARLOS SILVA F", - ("JOSE", "CARLOS SILVA", "F", "", ()), ("JOSE", "CARLOS SILVA", "F", "", ())), + ("JOSE", "CARLOS SILVA", "F", "", ()), ("JOSE", "CARLOS", "SILVA F", "", ())), ("PT_BR", "Pedro Alves N.", - ("Pedro", "Alves", "N.", "", ()), ("Pedro", "Alves", "N.", "", ())), + ("Pedro", "Alves", "N.", "", ()), ("Pedro", "", "Alves N.", "", ())), # the letter as an initial: before the surname, or leading, unchanged ("PT_BR", "JOHN F KENNEDY", ("JOHN", "F", "KENNEDY", "", ()), ("JOHN", "F", "KENNEDY", "", ())), @@ -3589,6 +3609,77 @@ def test_a_gaelic_pack_keeps_the_mac_masks( assert str(parser.capitalized(parser.parse(name))) == repaired +def test_the_portuguese_country_packs_read_two_family_names_and_pt_does_not() -> None: + # decisions/O6, 2026-11-19: pt-BR.toml and pt-PT.toml each hold a + # [rules] table and pt.toml none, so the pack chosen by language + # leaves O6 off; both country packs carry one Portuguese list + from nameparser._locale import rules_patch + from nameparser._reading_index import changed_words, selected + from nameparser.locales import pt_pt as _pt_pt + from nameparser.locales._pt_given_names import GIVEN_NAMES + on = PolicyPatch(two_family_names=True) + assert locales.PT_BR == Locale(code="pt_br", lexicon=Lexicon(given_names=GIVEN_NAMES), + policy=on, languages=frozenset({"pt-BR"})) + assert locales.PT_PT == Locale(code="pt_pt", lexicon=Lexicon(given_names=GIVEN_NAMES), + policy=on, languages=frozenset({"pt-PT"})) + assert locales.PT.policy == PolicyPatch() and not locales.PT.lexicon.given_names + # no table rides along a tag's ancestors: pt holds none, and a bare + # choice of either country's tag turns nothing on + with pytest.raises(KeyError, match="no vocabulary file 'pt'"): + rules_patch("pt") + for tag in ("pt-BR", "pt-PT"): + bare = parser_for(Locale(code="choice", lexicon=Lexicon.empty(), + languages=frozenset({tag}))) + assert not bare.policy.two_family_names, tag + assert not parser_for(locales.PT).policy.two_family_names + # pt-PT.toml holds no word, so pt_pt's choice selects pt's file alone + assert selected(locales.PT_PT.languages) == {"pt"} + assert (changed_words(selected(locales.PT_PT.languages)) + == changed_words(selected(locales.PT.languages))) + pt, br, pp = (_require_packed(c) for c in ("pt", "pt_br", "pt_pt")) + assert pt.parse("Rui Sousa Pinto").family == "Pinto" + assert pt.parse("Pedro Sousa Alves Filho").family == "Alves" + for packed, packed_pack in ((br, locales.PT_BR), (pp, locales.PT_PT)): + # two family names where pt reads a middle name + assert packed.parse("Rui Sousa Pinto").family == "Sousa Pinto" + # a listed given name stays, with its ç or with the c an ASCII + # writer puts in its place + for text in ("Ana Beatriz Costa", "Pedro Gonçalo Matos", + "Pedro Goncalo Matos", "Maria Constanca Reis"): + assert packed.parse(text).as_dict() == pt.parse(text).as_dict(), text + # a word the list lacks is taken, the switch's cost (rules/O6) + assert packed.parse("Ana Zzarita Costa").family == "Zzarita Costa" + # a family comma: the switch takes nothing from the given part + assert packed.parse("Pinto, Rui Sousa").as_dict() == pt.parse( + "Pinto, Rui Sousa").as_dict() + assert packed.parse("Rui Sousa Pinto, Jr.").family == "Sousa Pinto" + # beside a particle: the switch takes the word before the unit, + # and the list keeps a given name there + assert packed.parse("Rui Costa dos Santos").family == "Costa dos Santos" + assert packed.parse("Rui Pedro dos Santos").as_dict() == pt.parse( + "Rui Pedro dos Santos").as_dict() + # an agnomen is peeled before the family is counted: three name + # words left take one, two take none + sousa = packed.parse("Pedro Sousa Alves Filho") + assert (sousa.family, sousa.suffix) == ("Sousa Alves", "Filho") + alves = packed.parse("Pedro Alves Filho") + assert (alves.family, alves.suffix) == ("Alves", "Filho") + # under a family-first order: the first two words, the list + # vetoing a given name standing second + for order, given in ((FAMILY_FIRST, "Ana"), (FAMILY_FIRST_GIVEN_LAST, "Beatriz")): + ordered = parser_for(packed_pack, base=Parser(policy=Policy(name_order=order))) + souza = ordered.parse("Sousa Pinto Ana Beatriz") + assert (souza.family, souza.given) == ("Sousa Pinto", given), order + assert ordered.parse("Costa Beatriz Ana").family == "Costa", order + assert ordered.parse("Costa Zzbeatriz Ana").family == "Costa Zzbeatriz", order + # pt_br's SB beside the switch, which pt_pt's choice does not read + sb = br.parse("JOSE ALVES LIMA SB") + assert (sb.family, sb.suffix) == ("ALVES LIMA", "SB") + assert pp.parse("JOSE ALVES LIMA SB").family == "LIMA SB" + assert _pt_pt.DEVIATES("Rui Sousa Pinto") + assert not _pt_pt.DEVIATES("Rui Pinto") + + def test_the_es_ar_pack_is_es_with_a_longer_given_name_list() -> None: # decisions/O6, 2026-11-04: es's choice (es-AR selects es.toml, no # file of its own) and es's [rules], with a list that holds es's diff --git a/tests/v2/test_pt_given_names.py b/tests/v2/test_pt_given_names.py new file mode 100644 index 000000000..68f0277fd --- /dev/null +++ b/tests/v2/test_pt_given_names.py @@ -0,0 +1,197 @@ +"""The Portuguese given-name list rules/O6's veto reads under +locales.PT_BR and locales.PT_PT (#1453), and offline checks on +tools/pt_given_names.py, which writes it. + +As for the Spanish lists (tests/v2/test_es_given_names.py), what a test +can hold is what no cutoff may change: no word the default vocabulary +reads as no name, every entry in the fold the parse matches by, the +module's block as the tool renders it, and the tool's tally and +selection on hand-built records. The tool's source is the +`orcid-researchers` local corpus, which no test reads. +""" +from __future__ import annotations + +import importlib.util +import sys +from collections import Counter +from pathlib import Path +from types import ModuleType + +import pytest + +from tests.checkout import HAS_CHECKOUT + +import nameparser +from nameparser import Lexicon, locales, parser_for +from nameparser._pipeline._vocab import given_name_key +from nameparser.locales import _pt_given_names + +_PATH = Path(__file__).parents[2] / "tools" / "pt_given_names.py" + + +def _load() -> ModuleType: + spec = importlib.util.spec_from_file_location("pt_given_names", _PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +tool = _load() + + +def _record(country: str, given: str, family: str) -> dict[str, str]: + return {"country": country, "given": given, "family": family, + "name": f"{given} {family}"} + + +def test_the_tool_writes_the_module_the_packs_import() -> None: + assert _pt_given_names.__file__ is not None + if HAS_CHECKOUT: + assert tool.MODULE == Path(_pt_given_names.__file__) + else: + package = _PATH.parents[1] / "nameparser" + installed = Path(nameparser.__file__).parent + assert (tool.MODULE.relative_to(package) + == Path(_pt_given_names.__file__).relative_to(installed)) + for pack in (locales.PT_BR, locales.PT_PT): + assert pack.lexicon.given_names == _pt_given_names.GIVEN_NAMES + # locales.PT, chosen by language, carries neither the list nor O6 + assert not locales.PT.lexicon.given_names + + +def test_the_list_holds_no_word_the_default_reads_as_no_name() -> None: + # A word the default reads as a particle, a title, a suffix or a + # connective is no given name the veto could mean (the Spanish + # tool's exclusion, which this tool shares) + sets = Lexicon.default()._sets + pool = (sets.particles | sets.conjunctions | sets.titles | sets.titles_ambiguous + | sets.suffix_acronyms | sets.suffix_words) + folded = {given_name_key(w) for entry in pool for w in entry.split()} + assert not _pt_given_names.GIVEN_NAMES & folded + # its negative control: the folded pool does hold the words a + # Portuguese name writes beside its given names + assert {"da", "dos", "e", "dr", "jr"} <= folded + + +def test_every_entry_is_written_in_the_fold_it_is_matched_by() -> None: + entries = _pt_given_names._RANKED + _pt_given_names._C_SPELLINGS + assert _pt_given_names._RANKED and len(set(entries)) == len(entries) + assert [w for w in entries if given_name_key(w) != w or not w.isalpha()] == [] + assert _pt_given_names.GIVEN_NAMES == frozenset(entries) + assert not any(len(w) == 1 for w in entries) + + +def test_a_c_spelling_is_a_listed_word_with_its_cedilla_dropped() -> None: + cedilla = {w.replace("ç", "c") for w in _pt_given_names._RANKED if "ç" in w} + assert _pt_given_names._C_SPELLINGS + assert set(_pt_given_names._C_SPELLINGS) <= cedilla + assert not any("ç" in w for w in _pt_given_names._C_SPELLINGS) + + +def test_the_module_block_is_what_the_tool_renders() -> None: + # the module imported, not the tool's path into a checkout, so the + # check runs against an installed package too + assert _pt_given_names.__file__ is not None + text = Path(_pt_given_names.__file__).read_text(encoding="utf-8") + block = tool.render(list(_pt_given_names._RANKED), + list(_pt_given_names._C_SPELLINGS)) + assert tool.rewrite(text, block) == text + + +def test_the_removed_words_are_out_of_the_list() -> None: + assert not set(tool.REMOVED) & _pt_given_names.GIVEN_NAMES + + +def test_the_tally_skips_the_held_out_records_and_the_other_countries() -> None: + records = [ + _record("PT", "Rui", "Held Out"), # PT's first: held out + _record("BR", "Ana", "Held Out"), # BR's first: held out + _record("PT", "Rui Miguel", "Sousa Pinto"), + _record("BR", "Ana Beatriz", "da Paz Lima"), + _record("AO", "Kiala", "Neto"), # another country + _record("BR", "Ana", ""), # an empty box + _record("PT", "M.", "D'Ávila"), # an initial; an elided word + ] + given, family = tool.tally(records, ("PT", "BR"), 1, {"da"}) + # the initial is counted, its full stop folded away, and select() + # drops it; a word holding an apostrophe is no word a list carries + assert given == Counter({"rui": 1, "miguel": 1, "ana": 1, "beatriz": 1, "m": 1}) + # `paz` stands behind the particle, a unit O6 takes whole, so it says + # nothing about the bare word; `da` itself is counted + assert family == Counter({"sousa": 1, "pinto": 1, "da": 1, "lima": 1}) + # with nothing held out the first records count too + given_all, _ = tool.tally(records, ("PT",), 0, ()) + assert given_all["rui"] == 2 + + +def test_the_selection_keeps_the_mostly_given_words_over_the_floor() -> None: + given = Counter({"ana": 100, "augusto": 7, "mateus": 6, "rute": 4, + "da": 90, "j": 50, "zelia": 5}) + family = Counter({"augusto": 3, "mateus": 3, "rute": 0, "zelia": 0}) + # mateus is 6 of 9 uses given (67%), under 0.7; rute has 4 uses, under + # the floor of 5; da is excluded; j writes an initial; zelia is removed + assert tool.select(given, family, {"da"}, 5, 0.7, removed={"zelia"}) == [ + "ana", "augusto"] + assert "mateus" in tool.select(given, family, set(), 5, 0.6) + assert "rute" in tool.select(given, family, set(), 4, 0.7) + + +def test_a_c_spelling_is_kept_where_its_merged_uses_pass_the_share() -> None: + # Goncalo stands for Gonçalo and for a Goncalo, so both count; an + # excluded spelling is no candidate; França, listed, is refused + # below, its c spelling standing mostly for a surname + given = Counter({"gonçalo": 89, "goncalo": 3, "françoise": 6, + "constança": 11}) + family = Counter({"gonçalo": 3, "françoise": 0}) + ranked = ["gonçalo", "constança", "françoise"] + assert tool.c_spellings(ranked, given, family, set(), 0.7) == [ + "goncalo", "constanca", "francoise"] + assert tool.c_spelling_uses(["gonçalo"], given, family, set()) == [ + ("goncalo", 92, 3)] + assert tool.c_spellings(["gonçalo"], given, family, {"goncalo"}, 0.7) == [] + surnames = Counter({"frança": 1}) + assert tool.c_spellings(["frança"], surnames, Counter({"frança": 50}), + set(), 0.7) == [] + + +def test_a_removed_word_is_out_of_the_ranks_and_the_c_spellings() -> None: + # a c spelling ranked on its own uses, and also the c spelling of a + # ranked ç word: removing it must keep it out of both, which + # select() alone does not (the ç word would put it back) + given = Counter({"gonçalo": 89, "goncalo": 9, "ana": 150}) + family = Counter({"gonçalo": 3}) + assert tool.build(given, family, set(), 5, 0.7) == ( + ["ana", "gonçalo", "goncalo"], []) + assert tool.build(given, family, set(), 5, 0.7, removed={"goncalo"}) == ( + ["ana", "gonçalo"], []) + # removing the ç word drops its c spelling too where that is no word + # ranked on its own uses + given2 = Counter({"gonçalo": 89, "ana": 150}) + assert tool.build(given2, family, set(), 5, 0.7) == (["ana", "gonçalo"], ["goncalo"]) + assert tool.build(given2, family, set(), 5, 0.7, removed={"gonçalo"}) == (["ana"], []) + assert tool.build(given2, family, set(), 5, 0.7, removed={"goncalo"}) == ( + ["ana", "gonçalo"], []) + + +@pytest.mark.parametrize(("pack", "name", "field", "value"), [ + # the c spelling an ASCII writer puts in place of the ç + ("PT_PT", "Pedro Goncalo Matos", "middle", "Goncalo"), + ("PT_PT", "Pedro Gonçalo Matos", "middle", "Gonçalo"), + # the cedilla written as a combining mark (its c spelling is listed + # too, so the accent rows below are what a wrong fold would fail) + ("PT_BR", "Pedro Gonçalo Matos", "middle", "Gonçalo"), + # an accent the fold drops, precomposed and as a combining mark + ("PT_BR", "Pedro Luís Matos", "middle", "Luís"), + ("PT_PT", "Ana Ine\u0302s Matos", "middle", "Ine\u0302s"), + # an accented word the list lacks is taken (the switch's cost) + ("PT_PT", "Pedro Zzimão Matos", "family", "Zzimão Matos"), + ("PT_BR", "PEDRO GONCALO MATOS", "middle", "GONCALO"), + # a word the list lacks is taken (rules/O6's cost) + ("PT_BR", "Pedro Zzarita Matos", "family", "Zzarita Matos"), +]) +def test_the_list_through_the_packs(pack: str, name: str, field: str, + value: str) -> None: + parsed = parser_for(getattr(locales, pack)).parse(name) + assert getattr(parsed, field) == value diff --git a/tests/v2/test_reading_index.py b/tests/v2/test_reading_index.py index 54399399c..082f55f6c 100644 --- a/tests/v2/test_reading_index.py +++ b/tests/v2/test_reading_index.py @@ -186,6 +186,8 @@ def test_a_tag_selects_its_own_file_and_its_ancestors_never_its_descendants() -> # spelling cannot silently select only the parent assert ri.selected(["pt-br"]) == {"pt-BR", "pt"} # a region no file holds selects what its language's file holds + assert ri.selected(["pt-AO"]) == {"pt"} + # nor does one whose file holds a [rules] table and no reading assert ri.selected(["pt-PT"]) == {"pt"} # no macrolanguage table: Malay does not select Indonesian assert ri.selected(["ms"]) == {"ms"} @@ -331,7 +333,17 @@ def test_a_strict_pool_holds_the_chosen_files_mul_and_native_script_only() -> No def test_a_file_holding_no_reading_is_chosen_only_strictly() -> None: empty = ri.files() - ri.tags() assert empty and ri.tags() <= ri.files() - for tag in sorted(empty): + # a region's file holding only a [rules] table (pt-PT.toml, #1453) + # is chosen plainly through its language's file, which holds readings, + # and strictly with it + regions = {tag for tag in empty if tag.split("-")[0] in ri.tags()} + assert regions == {"pt-PT"} + for tag in sorted(regions): + language = tag.split("-")[0] + assert ri.selected([tag]) == ri.selected([language]) + assert ri.selected([tag], strict=True) == {tag} | ri.selected([language], strict=True) + assert not any(r.tag == tag for r in ri.index()) + for tag in sorted(empty - regions): with pytest.raises(ValueError, match=f"{tag}.toml holds no reading a parse reads"): ri.selected([tag]) @@ -392,6 +404,7 @@ def test_a_file_holding_only_familiar_readings_is_chosen_only_strictly( "nl": {"den", "ten", "tho"}, "pt": {"da", "do", "santa"}, "pt-BR": {"da", "do", "santa"}, + "pt-PT": {"da", "do", "santa"}, "sk": {"st"}, "sl": {"st"}, } diff --git a/tests/v2/test_vocab.py b/tests/v2/test_vocab.py index e41d1a75a..24fa12f0d 100644 --- a/tests/v2/test_vocab.py +++ b/tests/v2/test_vocab.py @@ -738,7 +738,7 @@ def test_every_mutation_starts_from_a_pool_the_checks_accept() -> None: # given reading beside a particle is fine once another given # reading of the word is on {"en.toml": _w('[[word]]\ntext = "zzq"\ncredential = {}\nfamily = { note = "x", default = false }')}, - {"pt-BR.toml": _w('[[word]]\ntext = "zzq"\nagnomen = { default = false }\nfamily = { note = "x", default = false }')}, + {"pt-AO.toml": _w('[[word]]\ntext = "zzq"\nagnomen = { default = false }\nfamily = { note = "x", default = false }')}, {"nl.toml": _w('[[word]]\ntext = "zzq"\ngiven = { note = "x", default = false }\npreposition = {}'), "en.toml": _w('[[word]]\ntext = "zzq"\ngiven = { note = "x" }\nexcluded = { title = "x" }')}, # check 11 met: a particle beside a given reading states nothing, @@ -786,7 +786,7 @@ def test_every_mutation_starts_from_a_pool_the_checks_accept() -> None: # refusing the generation word leaves an acronym reading free {"fr.toml": _w('[[word]]\ntext = "fils"\nexcluded = { generation = "Marie Fils" }'), "und.toml": _w('[[word]]\ntext = "fils"\ncredential = {}')}, - {"pt-BR.toml": OK, "zh-Hant.toml": _w('[[word]]\ntext = "社長"\nprofessional_honorific = {}'), + {"pt-AO.toml": OK, "zh-Hant.toml": _w('[[word]]\ntext = "社長"\nprofessional_honorific = {}'), "es-419.toml": _w('[[word]]\ntext = "sr"\ngeneration = {}')}, # check 10's order, met: kinds in CATEGORY order, a head before # its spellings, a refusal under the kind it refuses, a name @@ -1658,7 +1658,7 @@ def test_the_pack_roster_names_shipped_packs_their_files_compile_into() -> None: assert set(build.PACK_RULES.values()) <= set(locales._REGISTRY) for tag, attr in build.PACK_RULES.items(): assert getattr(locales, attr).policy == rules_patch(tag), attr - with pytest.raises(KeyError, match="no vocabulary file 'en' holds a \\[rules\\] table; the files that do: cs, es, ne, ru, sk, tr, vi"): + with pytest.raises(KeyError, match="no vocabulary file 'en' holds a \\[rules\\] table; the files that do: cs, es, ne, pt-BR, pt-PT, ru, sk, tr, vi"): rules_patch("en") diff --git a/tools/differential/cldr_agreement.py b/tools/differential/cldr_agreement.py index 1acd8f252..d0be82d99 100644 --- a/tools/differential/cldr_agreement.py +++ b/tools/differential/cldr_agreement.py @@ -170,8 +170,9 @@ "my": "MY"} #: Packs with no CLDR file to measure them on. CLDR's pt is Brazilian, #: read with PT_BR, which chooses PT's language and more; CLDR 48 has no -#: pt_PT names file, and no es_AR one (its es is read with ES). -NO_CLDR: frozenset[str] = frozenset({"PT", "ES_AR"}) +#: pt_PT names file, so PT_PT has none either, and no es_AR one (its es +#: is read with ES). +NO_CLDR: frozenset[str] = frozenset({"PT", "PT_PT", "ES_AR"}) #: The locale view of the native-script Wikidata source: stratum label -> #: the pack its renderings are parsed with (its QID file names no language). NATIVE_LABELS = {"zh-cn": "ZH", "zh-tw": "ZH", "ja-jp": "JA", "ne-np": "NE", diff --git a/tools/differential/cldr_agreement_locales.json b/tools/differential/cldr_agreement_locales.json index 7aa057b00..75fb625a1 100644 --- a/tools/differential/cldr_agreement_locales.json +++ b/tools/differential/cldr_agreement_locales.json @@ -1576,10 +1576,34 @@ } }, "pt/foreignFull/givenFirst": { + "family": { + "expected": "von Brühl", + "got": "Martín von Brühl" + }, + "family_base": { + "expected": "Brühl", + "got": "Martín Brühl" + }, + "given_names": { + "expected": "Mary Lou Cesare Martín", + "got": "Mary Lou Cesare" + }, "suffix": { "expected": "Jr. Dr. Ph.D", "got": "Jr., Ph.D" }, + "surname1_base": { + "expected": "Brühl", + "got": "Martín" + }, + "surname1_particles": { + "expected": "von", + "got": "" + }, + "surname2": { + "expected": "", + "got": "von Brühl" + }, "text": "Prof. Dr. Mary Lou Cesare Martín von Brühl Jr., Dr. Ph.D", "title": { "expected": "Prof. Dr.", @@ -1587,24 +1611,66 @@ } }, "pt/foreignFull/surnameFirst": { + "family": { + "expected": "von Brühl", + "got": "von Brühl Prof." + }, + "family_base": { + "expected": "Brühl", + "got": "Brühl Prof." + }, "given_names": { "expected": "Mary Lou Cesare Martín", - "got": "Prof. Dr. Mary Lou Cesare Martín" + "got": "Dr. Mary Lou Cesare Martín" }, "suffix": { "expected": "Jr. Dr. Ph.D", "got": "Jr., Ph.D" }, + "surname2": { + "expected": "", + "got": "Prof." + }, "text": "von Brühl Prof. Dr. Mary Lou Cesare Martín Jr., Dr. Ph.D", "title": { "expected": "Prof. Dr.", "got": "Dr." } }, - "pt/nativeFull/surnameFirst": { + "pt/foreignGGS/givenFirst": { + "family": { + "expected": "Stöber", + "got": "Hamish Stöber" + }, + "given_names": { + "expected": "Zäzilia Hamish", + "got": "Zäzilia" + }, + "text": "Zäzilia Hamish Stöber" + }, + "pt/foreignGGS/surnameFirst": { + "family": { + "expected": "Stöber", + "got": "Stöber Zäzilia" + }, "given_names": { - "expected": "José Pedro Eduardo", - "got": "Sr. José Pedro Eduardo" + "expected": "Zäzilia Hamish", + "got": "Hamish" + }, + "text": "Stöber Zäzilia Hamish" + }, + "pt/nativeFull/surnameFirst": { + "family": { + "expected": "da Silva", + "got": "da Silva Sr." + }, + "family_base": { + "expected": "Silva", + "got": "Silva Sr." + }, + "surname2": { + "expected": "", + "got": "Sr." }, "text": "da Silva Sr. José Pedro Eduardo Jr., MP", "title": { diff --git a/tools/differential/config_diff.py b/tools/differential/config_diff.py index 535e6dba8..94f91b82c 100644 --- a/tools/differential/config_diff.py +++ b/tools/differential/config_diff.py @@ -592,7 +592,7 @@ def _spellings(value: str) -> tuple[str, ...]: "NI": ("es",), "NL": ("nl",), "NO": ("nb", "nn"), "NP": ("ne",), "NZ": ("en", "mi"), "OM": ("ar",), "PA": ("es",), "PE": ("es",), "PF": ("fr",), "PG": ("en",), "PH": ("fil", "en"), "PK": ("ur", "pa", "sd", "en"), "PL": ("pl",), "PR": ("es", "en"), - "PS": ("ar",), "PT": ("pt",), "PY": ("es",), "QA": ("ar",), "RE": ("fr",), + "PS": ("ar",), "PT": ("pt-PT",), "PY": ("es",), "QA": ("ar",), "RE": ("fr",), "RO": ("ro",), "RS": ("sr",), "RU": ("ru",), "RW": ("fr", "en"), "SA": ("ar",), "SC": ("en", "fr"), "SD": ("ar",), "SE": ("sv",), "SG": ("zh", "ms", "ta", "en"), "SI": ("sl",), "SK": ("sk",), "SL": ("en",), "SN": ("fr", "ff"), "SO": ("ar",), @@ -743,7 +743,9 @@ def gap_specs(tag: str) -> tuple[str, str]: choosing it, or else the packs choosing no language whose code is it stacked with the bare tag (a strict call needs a language), or else the bare tag. A file holding no reading is refused as a plain - choice (it would change nothing), so its plain side is the default.""" + choice (it would change nothing), so its plain side is the default, + unless its language's file holds readings (pt-PT.toml, a [rules] + table alone), which a plain choice of the tag selects.""" from nameparser import _reading_index, locales packs = [locales.get(c) for c in sorted(locales.available())] items = [p.code.upper() for p in packs if tag in p.languages] @@ -751,8 +753,11 @@ def gap_specs(tag: str) -> tuple[str, str]: items = [p.code.upper() for p in packs if not p.languages and _pack_tag(p.code) == tag] + [tag] joined = "+".join(items) - return (f"plain:{joined}" if tag in _reading_index.tags() else "default", - f"strict:{joined}") + try: + _reading_index.selected([tag]) + except ValueError: + return "default", f"strict:{joined}" + return f"plain:{joined}", f"strict:{joined}" # --- gaps: the report -------------------------------------------------------------- diff --git a/tools/differential/corpus_rules.jsonl b/tools/differential/corpus_rules.jsonl index 44575a273..a2652ef4b 100644 --- a/tools/differential/corpus_rules.jsonl +++ b/tools/differential/corpus_rules.jsonl @@ -559,6 +559,7 @@ "JOHN SMITH, VD MA" "JOHN ST CLAIR" "JOHN V" +"JOSE CARLOS F" "JOSE CARLOS SILVA F" "JOSE CARLOS SILVA SB" "JOSE DA SILVA FH" diff --git a/tools/differential/snapshot.jsonl b/tools/differential/snapshot.jsonl index f5150b4a0..52f14dde0 100644 --- a/tools/differential/snapshot.jsonl +++ b/tools/differential/snapshot.jsonl @@ -1707,6 +1707,7 @@ {"name": "JOHN SMITH, VD MA", "given": "JOHN", "family": "SMITH", "suffix": "VD MA", "ambiguities": ["SUFFIX_OR_NAME"], "alternatives": ["SUFFIX_OR_NAME: name as given (position)"], "initials": "J. S.", "capitalized": "John Smith, VD MA"} {"name": "JOHN ST CLAIR", "given": "JOHN", "family": "ST CLAIR", "initials": "J. C.", "capitalized": "John St Clair"} {"name": "JOHN V", "given": "JOHN", "family": "V", "ambiguities": ["ORDER", "SUFFIX_OR_NAME"], "alternatives": ["SUFFIX_OR_NAME: generation as suffix (vocabulary)"], "initials": "J. V.", "capitalized": "John V"} +{"name": "JOSE CARLOS F", "given": "JOSE", "middle": "CARLOS", "family": "F", "initials": "J. C. F.", "capitalized": "Jose Carlos F"} {"name": "JOSE CARLOS SILVA F", "given": "JOSE", "middle": "CARLOS SILVA", "family": "F", "initials": "J. C. S. F.", "capitalized": "Jose Carlos Silva F"} {"name": "JOSE CARLOS SILVA SB", "given": "JOSE", "middle": "CARLOS SILVA", "family": "SB", "initials": "J. C. S. S.", "capitalized": "Jose Carlos Silva Sb"} {"name": "JOSE DA SILVA FH", "given": "JOSE", "family": "DA SILVA", "suffix": "FH", "ambiguities": ["SUFFIX_OR_NAME"], "alternatives": ["SUFFIX_OR_NAME: name as family (declared)"], "initials": "J. S.", "capitalized": "Jose da Silva Fh", "generation": "FH"} diff --git a/tools/pt_given_names.py b/tools/pt_given_names.py new file mode 100644 index 000000000..ea227da58 --- /dev/null +++ b/tools/pt_given_names.py @@ -0,0 +1,258 @@ +"""Build the Portuguese given-name list rules/O6's veto reads under +locales.PT_BR and locales.PT_PT (#1453). + +WHY THIS IS IN THE TREE. `Policy(two_family_names=True)` (rules/O6) +moves the name word before the family into the family, and in "Ana +Beatriz Costa" that word is a given name. A reader settles it by +vocabulary, as tools/es_given_names.py's lists settle it for Spanish +(#959), so O6 leaves a listed given name where it stands. No census +table of given names by count for Portugal or Brazil has been used +yet (decisions/O6, 2026-11-19, leaves one open), so the list is +measured on the names ORCID's holders split themselves: + +- ORCID's public data file (CC0), as tools/differential/local_orcid.py + extracts it into the `orcid-researchers` local corpus: each holder's + given-names box and family-name box, and the country they work or + live in. + +A word's given uses are the given boxes holding it, its family uses +the family boxes holding it, less a word written right after a word +the default reads as a particle ("da Paz"), a surname unit O6 takes +whole and the veto never reads, over the records of Portugal and +Brazil past the first HELD_OUT of each country in the corpus's order: +`config_diff.py score --cap HELD_OUT` scores the first HELD_OUT, so +the records that build the list are never the records it is scored on +(decisions/O6, 2026-11-19). One list serves both countries: lists cut +from each country's records alone read fewer of its own held-out +records than the pooled one (the same entry). + +A word is a candidate where it has at least MIN_USES uses and at +least SHARE of them are given uses; the list is every candidate, +ranked by given uses. Words the default vocabulary lists as a +particle, a conjunction, a title or a suffix are left out, as the +Spanish tool leaves them out (its `excluded_words`), and so are +words of one letter, which write an initial. The floor and SHARE are +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. + +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, +as the Spanish lists list an ñ word with n (#1081): data from systems +without the letter writes "Goncalo" for Gonçalo, and `given_name_key` +keeps the cedilla, so the fold runs one way through generated entries. + +Standard output is the list: each ranked word with its uses, then +each c spelling (a `c` row with its summed uses and share); a refused +c spelling is reported on standard error. `--words` prints any words' +tallied uses. + + uv run python tools/pt_given_names.py + uv run python tools/pt_given_names.py --write + uv run python tools/pt_given_names.py --min-uses 3 --share 0.8 + uv run python tools/pt_given_names.py --countries PT --min-uses 5 \\ + | awk '$1 ~ /^[0-9]+$/ {print $2}' > LIST # a candidate list + uv run python tools/pt_given_names.py --words Augusto Socorro + +The corpus is read from the local-corpus cache ($NAMEPARSER_TOOLS_CACHE +or ~/.cache/nameparser-tools); `uv run python +tools/differential/local_corpora.py fetch orcid-researchers` builds it. +""" +from __future__ import annotations + +import argparse +import sys +from collections import Counter +from collections.abc import Iterable, Mapping, Sequence +from pathlib import Path + +HERE = Path(__file__).parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE / "differential")) +import es_given_names # noqa: E402 (a sibling script, not a package) + +MODULE = HERE.parent / "nameparser" / "locales" / "_pt_given_names.py" +SOURCE = "orcid-researchers" +#: The countries whose records build the list, as ORCID writes them. +COUNTRIES = ("PT", "BR") +#: The records of each country set aside for scoring, the first in the +#: corpus's order: config_diff.py score's --cap reads the same ones. +HELD_OUT = 3000 +#: The decided floor and share (decisions/O6, 2026-11-19). +MIN_USES = 5 +SHARE = 0.7 +#: Words the cut keeps that the hand reading took out, each with why +#: (decisions/O6, 2026-11-19). +REMOVED: Mapping[str, str] = {} + +BEGIN = "# -- BEGIN generated by tools/pt_given_names.py; edit the tool, not this block --" +END = "# -- END generated --" + +fold = es_given_names.fold + + +def tally(records: Iterable[Mapping[str, str]], countries: Sequence[str], + held_out: int, after: Iterable[str] + ) -> tuple[Counter[str], Counter[str]]: + """Each word's given and family uses over `records` of `countries` + past the first `held_out` of each, both boxes filled; a family word + written right after one of `after` is not counted (a unit O6 takes + whole). A word holding anything but letters is left out, as the + Spanish tool's `words` leaves it out.""" + given: Counter[str] = Counter() + family: Counter[str] = Counter() + seen: Counter[str] = Counter() + particles = frozenset(after) + for record in records: + country = record.get("country", "") + if country not in countries: + continue + seen[country] += 1 + if seen[country] <= held_out: + continue + g, f = record.get("given", "").strip(), record.get("family", "").strip() + if not (g and f): + continue + given.update(es_given_names.words(g)) + written = es_given_names.words(f) + family.update(w for i, w in enumerate(written) + if not (i and written[i - 1] in particles)) + return given, family + + +def select(given: Counter[str], family: Counter[str], excluded: set[str], + min_uses: int = MIN_USES, share: float = SHARE, + removed: Iterable[str] = ()) -> list[str]: + """The words of at least `min_uses` uses at least `share` of which + are given uses, most given uses first, less `excluded` (the default + vocabulary's non-name readings), `removed` and words of one letter.""" + out = set(removed) + return sorted( + (w for w, g in given.items() + if len(w) > 1 and w not in excluded and w not in out + and g + family[w] >= min_uses and g >= share * (g + family[w])), + key=lambda w: (-given[w], w)) + + +def c_spelling_uses(ranked: list[str], given: Counter[str], family: Counter[str], + excluded: set[str]) -> list[tuple[str, int, int]]: + """Each candidate c spelling of a `ranked` word written with ç, in + rank order, with its given and family uses summed over every + spelling it stands for: an ASCII writer turns Gonçalo and a Goncalo + alike into "Goncalo", so both count. A spelling already listed or + `excluded` is no candidate.""" + def c(word: str) -> str: + return word.replace("ç", "c") + merged_given: Counter[str] = Counter() + merged_family: Counter[str] = Counter() + for word, count in given.items(): + merged_given[c(word)] += count + for word, count in family.items(): + merged_family[c(word)] += count + listed = set(ranked) + return [(c(word), merged_given[c(word)], merged_family[c(word)]) + for word in ranked + if c(word) != word and c(word) not in listed and c(word) not in excluded] + + +def c_spellings(ranked: list[str], given: Counter[str], family: Counter[str], + excluded: set[str], share: float = SHARE) -> list[str]: + """The candidate c spellings (`c_spelling_uses`) passing the + `share` test over their summed uses, in rank order.""" + return [word for word, g, f in c_spelling_uses(ranked, given, family, excluded) + if g >= share * (g + f)] + + +def build(given: Counter[str], family: Counter[str], excluded: set[str], + min_uses: int = MIN_USES, share: float = SHARE, + removed: Iterable[str] = ()) -> tuple[list[str], list[str]]: + """The list: the ranked words (`select`) and their c spellings + (`c_spellings`), a word in `removed` out of both, so a c spelling + the hand reading took out is no candidate either.""" + out = set(removed) + ranked = select(given, family, excluded, min_uses, share, out) + return ranked, c_spellings(ranked, given, family, excluded | out, share) + + +def render(ranked: list[str], spellings: list[str]) -> str: + def rows(words: list[str]) -> str: + lines = [", ".join(f'"{w}"' for w in words[i:i + 8]) + for i in range(0, len(words), 8)] + return "\n".join(f" {line}," for line in lines) + return (f"{BEGIN}\n_RANKED = (\n{rows(ranked)}\n)\n" + f"_C_SPELLINGS = (\n{rows(spellings)}\n)\n{END}") + + +def rewrite(module_text: str, block: str) -> str: + start, end = module_text.find(BEGIN), module_text.find(END) + if start < 0 or end < start: + raise ValueError(f"{MODULE} has no generated block to replace") + return module_text[:start] + block + module_text[end + len(END):] + + +def load_records() -> list[dict[str, str]]: + """The corpus's fielded records, in its order.""" + import local_agreement + import local_corpora + return list(local_agreement.records(local_corpora.require(SOURCE))) + + +def particles() -> set[str]: + """The default's particles, folded as the list is: a family word + written after one is not counted.""" + from nameparser import Lexicon + return {fold(w) for entry in Lexicon.default()._sets.particles for w in entry.split()} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + 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) + parser.add_argument("--share", type=float, default=SHARE) + parser.add_argument("--held-out", type=int, default=HELD_OUT, + help="records of each country left for scoring") + parser.add_argument("--countries", default=",".join(COUNTRIES), + help="the countries whose records build the list") + parser.add_argument("--words", nargs="+", metavar="WORD", + help="print these words' given and family uses " + "as tallied, and nothing else") + args = parser.parse_args(argv) + countries = tuple(args.countries.split(",")) + if args.write and (args.min_uses, args.share, args.held_out, countries) != ( + MIN_USES, SHARE, HELD_OUT, COUNTRIES): + parser.error("--write writes the decided cut; change the constants " + "in the tool, not the flags") + excluded = es_given_names.excluded_words() + given, family = tally(load_records(), countries, args.held_out, particles()) + if not given: + raise SystemExit(f"no record of {', '.join(countries)} past the first " + f"{args.held_out} holds both boxes") + if args.words: + for word in map(fold, args.words): + print(f"{word:20} given {given[word]:>7,} family {family[word]:>7,}") + return 0 + ranked, spellings = build(given, family, excluded, args.min_uses, args.share, REMOVED) + for i, word in enumerate(ranked, 1): + print(f"{i:5} {word:20} given {given[word]:>7,} family {family[word]:>7,}") + for word, g, f in c_spelling_uses(ranked, given, family, excluded | set(REMOVED)): + kept = word in spellings + print(f" c {word:20} given {g:>7,} family {f:>7,} " + f"{g / (g + f):.1%} given, {'kept' if kept else 'refused'}", + file=sys.stdout if kept else sys.stderr) + for word, why in REMOVED.items(): + print(f"removed {word:20} given {given[word]:>7,} family {family[word]:>7,}" + f" {why}", file=sys.stderr) + covered = sum(given[w] for w in ranked) + print(f"{len(ranked)} words, {covered / sum(given.values()):.1%} of " + "given-word uses", file=sys.stderr) + if args.write: + MODULE.write_text(rewrite(MODULE.read_text(encoding="utf-8"), + render(ranked, spellings)), encoding="utf-8") + print(f"wrote {MODULE}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/vocab/build.py b/tools/vocab/build.py index ee68e2359..64deebd76 100644 --- a/tools/vocab/build.py +++ b/tools/vocab/build.py @@ -361,9 +361,13 @@ def _alnum(text: str) -> str: #: packs. TR_AZ reads tr.toml's: no az.toml exists, and the pack's rule #: is one rule for both languages. ES_AR reads es.toml's too, a country #: pack reading its language's table (decisions/O6, 2026-11-04); the -#: roster names the one pack a file is listed for. +#: roster names the one pack a file is listed for. pt-BR.toml and +#: pt-PT.toml are country files holding a table their language's file +#: does not: locales.PT, chosen for Portuguese names from any country, +#: leaves O6 off (decisions/O6, 2026-11-19). PACK_RULES: dict[str, str] = {"ru": "RU", "tr": "TR_AZ", "es": "ES", "cs": "CS", - "sk": "SK", "vi": "VI", "ne": "NE"} + "sk": "SK", "vi": "VI", "ne": "NE", + "pt-BR": "PT_BR", "pt-PT": "PT_PT"} #: The words check 13 lets hold a reading in another file beside their #: mul.toml one, each with why (#1005): `i` is mul.toml's numeral and