prenomen 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prenomen/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """Prenomen: hybrid dictionary + LLM gender inference from personal names.
2
+
3
+ from prenomen import Prenomen
4
+
5
+ p = Prenomen(model="gpt-4o-mini", base_url="https://api.openai.com/v1",
6
+ api_key_env="OPENAI_API_KEY", dictionaries=["wgnd"])
7
+ print(p.infer("Marie", "Curie", countries=["FR"]).gender)
8
+
9
+ One name in, one result out. Reading tables, iterating them and writing results are
10
+ the caller's; see ``examples/batch.py``. Building a Prenomen is expensive, so build
11
+ one per process and reuse it.
12
+ """
13
+
14
+ from importlib.metadata import PackageNotFoundError, version
15
+
16
+ try:
17
+ # One source of truth: the version declared in pyproject.toml, read back from
18
+ # the installed distribution rather than restated here where it would drift.
19
+ __version__ = version("prenomen")
20
+ except PackageNotFoundError: # a source tree that was never installed
21
+ __version__ = "0.0.0+unknown"
22
+
23
+ # Names resolved on first access rather than imported here, so `import prenomen`
24
+ # costs nothing: `Prenomen` pulls in openai, jinja2 and pandas (about a second and a
25
+ # half), which a caller who only wants `split_full_name` or the dictionary
26
+ # downloader should not pay.
27
+ _LAZY = {
28
+ "Prenomen": ".inference",
29
+ "DictionarySpec": ".dict_lookup",
30
+ "ALL_DICTIONARIES": ".dictionaries",
31
+ "dictionary_dir": ".dictionaries",
32
+ }
33
+
34
+ from .models import DictMatch, Gender, ReasoningCode
35
+ from .names import split_full_name
36
+ from .results import GenderResult, NameQuery, Verdict
37
+
38
+ __all__ = [
39
+ "ALL_DICTIONARIES",
40
+ "DictMatch",
41
+ "DictionarySpec",
42
+ "Gender",
43
+ "GenderResult",
44
+ "NameQuery",
45
+ "Prenomen",
46
+ "ReasoningCode",
47
+ "Verdict",
48
+ "__version__",
49
+ "dictionary_dir",
50
+ "split_full_name",
51
+ ]
52
+
53
+
54
+ def __getattr__(name):
55
+ module = _LAZY.get(name)
56
+ if module is None:
57
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
58
+ from importlib import import_module
59
+
60
+ return getattr(import_module(module, __name__), name)
61
+
62
+
63
+ def __dir__():
64
+ return sorted(__all__)
prenomen/client.py ADDED
@@ -0,0 +1,57 @@
1
+ """Client for the OpenAI-compatible endpoint."""
2
+
3
+ import logging
4
+ import os
5
+
6
+ from openai import OpenAI
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ FALLBACK_ENV = "OPENAI_API_KEY"
11
+
12
+
13
+ def resolve_api_key(api_key: str | None = None, api_key_env: str | None = None) -> str:
14
+ """Return the API key, preferring the environment over a literal.
15
+
16
+ ``api_key_env`` names an environment variable and is the way to pass a real
17
+ credential, so keys stay out of files that get committed; naming one that is
18
+ unset is an error rather than a silent fallback. A literal ``api_key`` is still
19
+ accepted, which is what local servers that ignore authentication want -- as is
20
+ passing neither, which falls back to ``$OPENAI_API_KEY`` and then to a dummy.
21
+ """
22
+ if api_key_env:
23
+ key = os.environ.get(api_key_env)
24
+ if not key:
25
+ raise ValueError(
26
+ f"api_key_env names {api_key_env!r} but that environment variable "
27
+ f"is unset. Export it, or pass a literal api_key for a local "
28
+ f"endpoint that ignores authentication."
29
+ )
30
+ return key
31
+ if api_key:
32
+ return api_key
33
+ return os.environ.get(FALLBACK_ENV) or "dummy"
34
+
35
+
36
+ def build_client(
37
+ base_url: str,
38
+ api_key: str,
39
+ *,
40
+ timeout: float = 120.0,
41
+ max_retries: int = 2,
42
+ ) -> OpenAI:
43
+ """Build the OpenAI client for one endpoint.
44
+
45
+ ``timeout`` and ``max_retries`` are the SDK's own, so a retry covers a timeout as
46
+ well as an error status. Constructing this opens no connection.
47
+ """
48
+ if not base_url or not isinstance(base_url, str):
49
+ raise ValueError(
50
+ "base_url must be the endpoint to call, for example "
51
+ '"https://api.openai.com/v1" or "http://localhost:8000/v1".'
52
+ )
53
+ base_url = base_url.rstrip("/")
54
+ logger.info(f"Endpoint: {base_url}")
55
+ return OpenAI(
56
+ base_url=base_url, api_key=api_key, timeout=timeout, max_retries=max_retries
57
+ )
prenomen/confidence.py ADDED
@@ -0,0 +1,133 @@
1
+ """Reliability-weighted confidence from name-gender dictionary matches.
2
+
3
+ :func:`weighted_dict_confidence` estimates P(dominant gender | name) from the
4
+ dictionaries alone, bounded in [0, 1]. The pipeline uses it for the bypass gate:
5
+ when the dictionaries are conclusive enough, the name is settled without a model
6
+ call. A single source reduces to its own frequency ratio, so a gate threshold of
7
+ 0.85 means exactly "frequency ratio >= 0.85".
8
+
9
+ Each dictionary that matched contributes p = frequency when it agrees with the
10
+ gender being scored, else 1 - frequency, where frequency is that source's empirical
11
+ P(gender | name). Matches without a frequency carry no evidence and are ignored.
12
+ Both genders are scored by that one rule and the higher score wins, so the gender
13
+ returned and the confidence attached to it always come from the same arithmetic.
14
+
15
+ Correlated dictionaries form a *family*: the family carries its reliability weight
16
+ once, split evenly across whichever of its members matched, so two near-duplicate
17
+ resources for the same language do not compound their weight against a broad one.
18
+ Family membership and weight come from each dictionary's spec, so adding a source
19
+ needs no code change. See :func:`source_meta_from_specs`.
20
+ """
21
+
22
+ import math
23
+ from collections import Counter
24
+ from collections.abc import Sequence
25
+ from dataclasses import dataclass
26
+
27
+ from .dictionaries import DictionarySpec
28
+ from .models import DictMatch, Gender
29
+
30
+ _GENDER_ORDER = {Gender.MALE: 0, Gender.FEMALE: 1} # deterministic tie-break
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SourceMeta:
35
+ """Reliability metadata for one dictionary source."""
36
+
37
+ family: str
38
+ weight: float
39
+
40
+
41
+ def source_meta_from_specs(
42
+ specs: Sequence[DictionarySpec],
43
+ ) -> dict[str, SourceMeta]:
44
+ """Build the source metadata map from the dictionary specs being used.
45
+
46
+ Each spec carries its own ``family`` (defaulting to its name) and ``weight``
47
+ (defaulting to 1.0), so the calibrated values for the shipped dictionaries live
48
+ in one place -- the registry in :mod:`prenomen.dictionaries` -- rather than being
49
+ restated here where they would drift. Sources sharing a family share one vote.
50
+ """
51
+ return {s.name: SourceMeta(family=s.family, weight=float(s.weight)) for s in specs}
52
+
53
+
54
+ def _resolve(source: str, meta: dict[str, SourceMeta] | None) -> SourceMeta:
55
+ """A source not described by any spec is a standalone family of weight 1."""
56
+ if meta and source in meta:
57
+ return meta[source]
58
+ return SourceMeta(source, 1.0)
59
+
60
+
61
+ def _member_weights(
62
+ found: list[DictMatch], meta: dict[str, SourceMeta] | None
63
+ ) -> list[float]:
64
+ """Weight per matched source, positionally aligned with ``found``.
65
+
66
+ Each family's weight is split evenly across the members of that family that
67
+ actually matched, so near-duplicate resources cast one vote between them.
68
+ """
69
+ resolved = [_resolve(m.source, meta) for m in found]
70
+ fam_counts = Counter(r.family for r in resolved)
71
+ return [r.weight / fam_counts[r.family] for r in resolved]
72
+
73
+
74
+ def weighted_dict_confidence(
75
+ dict_matches: list[DictMatch],
76
+ source_meta: dict[str, SourceMeta] | None = None,
77
+ ) -> tuple[Gender, float] | None:
78
+ """Dominant gender and the reliability-weighted mean of P(dominant | name).
79
+
80
+ Both genders are scored as::
81
+
82
+ score(g) = sum(w_s * p_s(g)) / sum(w_s)
83
+
84
+ with p_s(g) = frequency_s if source s names g else 1 - frequency_s, and w_s the
85
+ source's reliability weight. The higher-scoring gender is returned with its own
86
+ score as the confidence, so the two can never contradict each other. The result
87
+ is bounded in [0, 1] and never below 0.5; a single source reduces to its own
88
+ frequency ratio. Returns ``None`` when no usable match is present.
89
+ """
90
+ found = [
91
+ m
92
+ for m in dict_matches
93
+ if m.found
94
+ and m.gender not in (None, Gender.NOT_RETRIEVABLE)
95
+ and m.frequency is not None
96
+ ]
97
+ if not found:
98
+ return None
99
+
100
+ weights = _member_weights(found, source_meta)
101
+ weight_sum = sum(weights)
102
+ if weight_sum == 0.0:
103
+ return None
104
+
105
+ # Score every candidate gender by the same rule that reports the confidence, so
106
+ # the gender returned and the number attached to it can never disagree. Scoring
107
+ # the winner separately from the vote lets two weak agreeing sources out-vote one
108
+ # strong opposing source and then be handed a confidence below 0.5.
109
+ def score(gender: Gender) -> float:
110
+ return (
111
+ sum(
112
+ w * (m.frequency if m.gender == gender else 1.0 - m.frequency)
113
+ for m, w in zip(found, weights)
114
+ )
115
+ / weight_sum
116
+ )
117
+
118
+ scores = {g: score(g) for g in (Gender.MALE, Gender.FEMALE)}
119
+
120
+ # A genuine tie is unresolvable from the dictionaries alone, so report maximal
121
+ # uncertainty (0.5) -- below any sane threshold, so it never bypasses. The gender
122
+ # is still returned deterministically (MALE-first).
123
+ top = max(scores.values())
124
+ tied = [
125
+ g
126
+ for g, s in scores.items()
127
+ if math.isclose(s, top, rel_tol=1e-9, abs_tol=1e-12)
128
+ ]
129
+ dominant = min(tied, key=lambda g: _GENDER_ORDER.get(g, 99))
130
+ if len(tied) > 1:
131
+ return dominant, 0.5
132
+
133
+ return dominant, scores[dominant]
prenomen/config.py ADDED
@@ -0,0 +1,150 @@
1
+ """Optional YAML configuration for :class:`~prenomen.inference.Prenomen`.
2
+
3
+ Configuration is Python first: every setting is a constructor argument. This module
4
+ exists because an endpoint, a model name and a list of dictionaries are the kind of
5
+ thing people like to keep in a file and share, and because the error messages for a
6
+ mistyped key are worth having in one place.
7
+
8
+ p = Prenomen.from_config("prenomen.yaml", max_workers=4)
9
+
10
+ Keyword arguments override the file. See ``examples/prenomen.yaml``.
11
+ """
12
+
13
+ import os
14
+ from typing import Any
15
+
16
+ import yaml
17
+
18
+
19
+ def load_yaml(path) -> dict:
20
+ """Parse one YAML config, reporting the usual mistakes as ValueError.
21
+
22
+ A missing path, a syntax error and an empty document all have to surface as the
23
+ one exception the caller can render as a single line instead of a traceback.
24
+ """
25
+ try:
26
+ with open(path, "rb") as f:
27
+ loaded = yaml.safe_load(f)
28
+ except FileNotFoundError:
29
+ raise ValueError(f"Config file not found: {path}") from None
30
+ except OSError as exc:
31
+ raise ValueError(f"{path}: cannot be read: {exc}") from exc
32
+ except yaml.YAMLError as exc:
33
+ raise ValueError(f"{path}: is not valid YAML: {exc}") from exc
34
+ if not isinstance(loaded, dict):
35
+ found = "an empty file" if loaded is None else type(loaded).__name__
36
+ raise ValueError(f"{path}: expected a YAML mapping, found {found}")
37
+ return loaded
38
+
39
+
40
+ def require(cfg: dict, path: str, where: str):
41
+ """Fetch a mandatory (possibly dotted) config key, naming the file if absent."""
42
+ node = cfg
43
+ for key in path.split("."):
44
+ if not isinstance(node, dict) or key not in node:
45
+ raise ValueError(f"{where}: missing required `{path}` setting")
46
+ node = node[key]
47
+ return node
48
+
49
+
50
+ def section(cfg: dict, name: str, where: str) -> dict:
51
+ """An optional block of settings, empty when absent.
52
+
53
+ ``name:`` with nothing under it parses as None, which is what commenting a
54
+ block out leaves behind. That reads as "no settings here", not as a crash.
55
+ """
56
+ value = cfg.get(name)
57
+ if value is None:
58
+ return {}
59
+ if not isinstance(value, dict):
60
+ raise ValueError(
61
+ f"{where}: `{name}:` must be a block of settings, "
62
+ f"found {type(value).__name__}"
63
+ )
64
+ return value
65
+
66
+
67
+ # Settings accepted under `inference:`, mapped to constructor arguments of the same
68
+ # name. Listed rather than passed through, so a typo is reported instead of ignored.
69
+ _INFERENCE_KEYS = (
70
+ "dict_bypass_threshold",
71
+ "max_workers",
72
+ "timeout",
73
+ "max_retries",
74
+ "cache_size",
75
+ "template_dir",
76
+ "preload",
77
+ )
78
+
79
+
80
+ # Settings accepted under `prompt:`: defaults for what the prompt says besides the name.
81
+ _PROMPT_KEYS = ("country_label", "context_labels")
82
+
83
+
84
+ def _settings(cfg: dict, name: str, accepted: tuple, where: str) -> dict:
85
+ """An optional block whose keys must all be in ``accepted``; a typo is reported."""
86
+ block = section(cfg, name, where)
87
+ unknown = sorted(set(block) - set(accepted))
88
+ if unknown:
89
+ raise ValueError(
90
+ f"{where}: unknown `{name}:` setting(s) {unknown}. Accepted: {list(accepted)}"
91
+ )
92
+ return block
93
+
94
+
95
+ def _dictionaries(raw, where: str):
96
+ """Read the ``dictionaries:`` list: names of shipped ones, or full specs."""
97
+ if raw is None:
98
+ return []
99
+ if not isinstance(raw, list):
100
+ raise ValueError(
101
+ f"{where}: `dictionaries:` must be a list of names or specs, found "
102
+ f"{type(raw).__name__}. For example:\n"
103
+ f" dictionaries:\n - wgnd\n - name: my_list\n"
104
+ f' path: "~/names.tsv"\n name_col: "name"'
105
+ )
106
+ from .dictionaries import DictionarySpec
107
+
108
+ out = []
109
+ for position, item in enumerate(raw):
110
+ if isinstance(item, str):
111
+ out.append(item)
112
+ elif isinstance(item, dict):
113
+ try:
114
+ out.append(DictionarySpec(**item))
115
+ except TypeError as exc:
116
+ raise ValueError(
117
+ f"{where}: dictionaries[{position}]: {exc}"
118
+ ) from exc
119
+ else:
120
+ raise ValueError(
121
+ f"{where}: dictionaries[{position}] must be a name or a mapping, "
122
+ f"found {type(item).__name__}"
123
+ )
124
+ return out
125
+
126
+
127
+ def config_to_kwargs(cfg: dict, where: str) -> dict[str, Any]:
128
+ """Translate a parsed config into Prenomen constructor arguments."""
129
+ api = section(cfg, "api", where)
130
+ if not api.get("base_url"):
131
+ raise ValueError(
132
+ f"{where}: needs an `api:` section naming the endpoint:\n"
133
+ f" api:\n"
134
+ f' base_url: "https://api.openai.com/v1"\n'
135
+ f' api_key_env: "OPENAI_API_KEY"'
136
+ )
137
+ kwargs: dict[str, Any] = {
138
+ "model": require(cfg, "model.name", where),
139
+ "base_url": api["base_url"],
140
+ "api_key": api.get("api_key"),
141
+ "api_key_env": api.get("api_key_env"),
142
+ "parameters": section(cfg, "parameters", where),
143
+ "dictionaries": _dictionaries(cfg.get("dictionaries"), where),
144
+ }
145
+ if cfg.get("dictionary_dir") is not None:
146
+ kwargs["dictionary_dir"] = os.path.expanduser(str(cfg["dictionary_dir"]))
147
+
148
+ kwargs.update(_settings(cfg, "inference", _INFERENCE_KEYS, where))
149
+ kwargs.update(_settings(cfg, "prompt", _PROMPT_KEYS, where))
150
+ return kwargs