BarraHome commited on
Commit
b602549
·
verified ·
1 Parent(s): acbf191

Sync the inference package

Browse files
.github/workflows/ci.yml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ verify:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+ cache: pip
25
+ - name: Install with a CPU-only torch
26
+ run: |
27
+ python -m pip install --upgrade pip build twine
28
+ python -m pip install -e . \
29
+ --extra-index-url https://download.pytorch.org/whl/cpu
30
+ # The same script that runs locally. A second copy of these checks
31
+ # written into this file would drift from the one people actually run.
32
+ - run: python verify.py --build
.github/workflows/publish.yml ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish
2
+
3
+ # Trusted Publishing: PyPI verifies this workflow's OIDC identity, so there is
4
+ # no API token to store or rotate. Configure it once at
5
+ # pypi.org/manage/account/publishing/ with the owner, the repository, this
6
+ # filename and the environment named below.
7
+ #
8
+ # Nothing is uploaded until verify.py passes on every supported Python and the
9
+ # tag matches the package version.
10
+ on:
11
+ release:
12
+ types: [published]
13
+ workflow_dispatch:
14
+ inputs:
15
+ dry_run:
16
+ description: "Build and verify without uploading"
17
+ type: boolean
18
+ default: true
19
+
20
+ permissions:
21
+ contents: read
22
+
23
+ jobs:
24
+ verify:
25
+ runs-on: ubuntu-latest
26
+ strategy:
27
+ fail-fast: true
28
+ matrix:
29
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
30
+ steps:
31
+ - uses: actions/checkout@v4
32
+ - uses: actions/setup-python@v5
33
+ with:
34
+ python-version: ${{ matrix.python-version }}
35
+ - run: |
36
+ python -m pip install --upgrade pip build twine
37
+ python -m pip install -e . \
38
+ --extra-index-url https://download.pytorch.org/whl/cpu
39
+ - run: python verify.py --build
40
+
41
+ build:
42
+ needs: verify
43
+ runs-on: ubuntu-latest
44
+ outputs:
45
+ version: ${{ steps.version.outputs.version }}
46
+ steps:
47
+ - uses: actions/checkout@v4
48
+ - uses: actions/setup-python@v5
49
+ with:
50
+ python-version: "3.12"
51
+ - id: version
52
+ name: Read the version from the package
53
+ run: |
54
+ version=$(python scripts/version.py)
55
+ echo "version=$version" >> "$GITHUB_OUTPUT"
56
+ echo "package version: $version"
57
+ - name: Refuse a tag that disagrees with the version
58
+ if: github.event_name == 'release'
59
+ run: |
60
+ tag="${GITHUB_REF_NAME#v}"
61
+ version="${{ steps.version.outputs.version }}"
62
+ if [ "$tag" != "$version" ]; then
63
+ echo "::error::release tag $tag does not match package version $version"
64
+ exit 1
65
+ fi
66
+ - name: Refuse a version already on PyPI
67
+ run: |
68
+ v="${{ steps.version.outputs.version }}"
69
+ url="https://pypi.org/pypi/decision-jef/$v/json"
70
+ code=$(curl -sS -o /dev/null -w "%{http_code}" "$url")
71
+ if [ "$code" = "200" ]; then
72
+ echo "::error::decision-jef $v is already published; bump the version"
73
+ exit 1
74
+ fi
75
+ - name: Build
76
+ run: |
77
+ python -m pip install --upgrade pip build twine
78
+ python -m build
79
+ python -m twine check dist/*
80
+ - uses: actions/upload-artifact@v4
81
+ with:
82
+ name: dist
83
+ path: dist/
84
+
85
+ publish:
86
+ needs: build
87
+ if: github.event_name == 'release' || inputs.dry_run == false
88
+ runs-on: ubuntu-latest
89
+ environment: pypi
90
+ permissions:
91
+ id-token: write # the only extra permission Trusted Publishing needs
92
+ steps:
93
+ - uses: actions/download-artifact@v4
94
+ with:
95
+ name: dist
96
+ path: dist/
97
+ - uses: pypa/gh-action-pypi-publish@release/v1
.gitignore CHANGED
@@ -1,2 +1,7 @@
1
  __pycache__/
2
  *.pyc
 
 
 
 
 
 
1
  __pycache__/
2
  *.pyc
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ .venv/
7
+ *.pt
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Decision-Jef contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
decision_jef/__init__.py CHANGED
@@ -16,7 +16,9 @@
16
  },
17
  )
18
  """
 
 
19
  from decision_jef.infer import Decider
20
  from decision_jef.wire import Answer, Question, Request
21
 
22
- __all__ = ["Decider", "Question", "Request", "Answer"]
 
16
  },
17
  )
18
  """
19
+ __version__ = "0.1.2"
20
+
21
  from decision_jef.infer import Decider
22
  from decision_jef.wire import Answer, Question, Request
23
 
24
+ __all__ = ["Decider", "Question", "Request", "Answer", "__version__"]
decision_jef/infer.py CHANGED
@@ -17,6 +17,10 @@ from decision_jef.model import DecisionJef
17
  from decision_jef.pack import pack
18
  from decision_jef.wire import Answer, Question, Request
19
 
 
 
 
 
20
 
21
  class Decider:
22
  def __init__(self, model: DecisionJef, tokenizer, temperatures=None,
@@ -43,7 +47,12 @@ class Decider:
43
 
44
  weights = grab("model.pt")
45
  if weights is None:
46
- raise FileNotFoundError("model.pt not found in " + repo_or_path)
 
 
 
 
 
47
  if device == "auto":
48
  device = "cuda" if torch.cuda.is_available() else "cpu"
49
  dev = torch.device(device)
@@ -85,6 +94,13 @@ class Decider:
85
  if calibrated:
86
  row = row / self._temp(kind, int(counts[i]))
87
  p = torch.softmax(row[: len(keys)], -1).cpu().tolist()
 
 
 
 
 
 
 
88
  d = {k: round(float(v), 4) for k, v in zip(keys, p)}
89
  best = max(d, key=d.get)
90
  out[qid] = Answer(
 
17
  from decision_jef.pack import pack
18
  from decision_jef.wire import Answer, Question, Request
19
 
20
+ # Two decimal places is what a reported probability is worth here, so a
21
+ # floor well below that costs no information and avoids claiming certainty.
22
+ PROB_FLOOR = 1e-4
23
+
24
 
25
  class Decider:
26
  def __init__(self, model: DecisionJef, tokenizer, temperatures=None,
 
47
 
48
  weights = grab("model.pt")
49
  if weights is None:
50
+ raise FileNotFoundError(
51
+ f"No model.pt in {repo_or_path!r}.\n"
52
+ "The weights are published separately from this package. If the "
53
+ "repository is private or gated, authenticate first with "
54
+ "`hf auth login`, or pass a local directory containing model.pt.\n"
55
+ "See https://huggingface.co/BarraHome/Decision-Jef-0.1")
56
  if device == "auto":
57
  device = "cuda" if torch.cuda.is_available() else "cpu"
58
  dev = torch.device(device)
 
94
  if calibrated:
95
  row = row / self._temp(kind, int(counts[i]))
96
  p = torch.softmax(row[: len(keys)], -1).cpu().tolist()
97
+ # Never report certainty. Sharpening temperatures (around 0.34
98
+ # here) can drive a confident logit gap to a rounded 1.0, and a
99
+ # probability of exactly 1 claims the answer cannot be wrong.
100
+ # Clamp and renormalise so the distribution still sums to 1.
101
+ p = [min(max(v, PROB_FLOOR), 1.0 - PROB_FLOOR) for v in p]
102
+ total = sum(p)
103
+ p = [v / total for v in p]
104
  d = {k: round(float(v), 4) for k, v in zip(keys, p)}
105
  best = max(d, key=d.get)
106
  out[qid] = Answer(
decision_jef/py.typed ADDED
File without changes
pyproject.toml CHANGED
@@ -1,22 +1,56 @@
1
  [build-system]
2
- requires = ["setuptools>=68"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "decision-jef"
7
- version = "0.1.0"
8
  description = "Typed decisions with calibrated probabilities, in one forward pass"
9
- readme = "README.md"
 
 
10
  requires-python = ">=3.10"
11
- license = { text = "MIT" }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  dependencies = [
13
  "torch>=2.4",
14
  "transformers>=4.48",
15
  "huggingface-hub>=0.26",
16
  ]
17
 
 
 
 
18
  [project.urls]
 
19
  Model = "https://huggingface.co/BarraHome/Decision-Jef-0.1"
 
 
 
 
 
 
20
 
21
  [tool.setuptools]
22
  packages = ["decision_jef"]
 
 
 
 
1
  [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
  build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "decision-jef"
7
+ dynamic = ["version"]
8
  description = "Typed decisions with calibrated probabilities, in one forward pass"
9
+ # README.md is the clean one. HF_CARD.md carries the model-card
10
+ # frontmatter and is uploaded to the Hub as its README.
11
+ readme = { file = "README.md", content-type = "text/markdown" }
12
  requires-python = ">=3.10"
13
+ license = "MIT"
14
+ license-files = ["LICENSE"]
15
+ keywords = [
16
+ "typed-decisions", "calibration", "classification", "routing",
17
+ "scoring", "encoder", "multilingual", "nlp",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Developers",
22
+ "Intended Audience :: Science/Research",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
30
+ "Topic :: Text Processing :: Linguistic",
31
+ "Typing :: Typed",
32
+ ]
33
  dependencies = [
34
  "torch>=2.4",
35
  "transformers>=4.48",
36
  "huggingface-hub>=0.26",
37
  ]
38
 
39
+ [project.optional-dependencies]
40
+ dev = ["pytest>=8"]
41
+
42
  [project.urls]
43
+ Homepage = "https://huggingface.co/BarraHome/Decision-Jef-0.1"
44
  Model = "https://huggingface.co/BarraHome/Decision-Jef-0.1"
45
+ Issues = "https://huggingface.co/BarraHome/Decision-Jef-0.1/discussions"
46
+
47
+ [tool.setuptools.dynamic]
48
+ # One source of truth. A version in two files drifts, and the tag check
49
+ # in the publish workflow would then pass against the wrong one.
50
+ version = { attr = "decision_jef.__version__" }
51
 
52
  [tool.setuptools]
53
  packages = ["decision_jef"]
54
+
55
+ [tool.setuptools.package-data]
56
+ decision_jef = ["py.typed"]
scripts/bump.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Bump the version, in the one place it lives.
3
+
4
+ python scripts/bump.py patch 0.1.0 -> 0.1.1
5
+ python scripts/bump.py minor 0.1.0 -> 0.2.0
6
+ python scripts/bump.py major 0.1.0 -> 1.0.0
7
+ python scripts/bump.py 0.3.0 set it outright
8
+
9
+ Then commit and tag: the publish workflow refuses a tag that disagrees with
10
+ the package version, and refuses a version already on PyPI.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ INIT = Path(__file__).resolve().parent.parent / "decision_jef" / "__init__.py"
20
+ PATTERN = re.compile(r'(__version__ = ")([^"]+)(")')
21
+
22
+
23
+ def main() -> int:
24
+ if len(sys.argv) != 2:
25
+ print(__doc__)
26
+ return 2
27
+ arg = sys.argv[1]
28
+ text = INIT.read_text()
29
+ match = PATTERN.search(text)
30
+ if match is None:
31
+ print(f"no __version__ in {INIT}", file=sys.stderr)
32
+ return 1
33
+ current = match.group(2)
34
+ major, minor, patch = (int(x) for x in current.split("."))
35
+
36
+ if arg == "major":
37
+ new = f"{major + 1}.0.0"
38
+ elif arg == "minor":
39
+ new = f"{major}.{minor + 1}.0"
40
+ elif arg == "patch":
41
+ new = f"{major}.{minor}.{patch + 1}"
42
+ elif re.fullmatch(r"\d+\.\d+\.\d+", arg):
43
+ new = arg
44
+ else:
45
+ print(f"not a bump or a version: {arg!r}", file=sys.stderr)
46
+ return 2
47
+
48
+ INIT.write_text(PATTERN.sub(rf"\g<1>{new}\g<3>", text, count=1))
49
+ print(f"{current} -> {new}")
50
+ print("\nnext:")
51
+ print(f" python verify.py --build")
52
+ print(f" git commit -am 'Release {new}' && git tag v{new}")
53
+ print(f" git push && git push --tags")
54
+ print(f" gh release create v{new} --generate-notes")
55
+ return 0
56
+
57
+
58
+ if __name__ == "__main__":
59
+ sys.exit(main())
scripts/version.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Print the package version without importing the package.
3
+
4
+ The publish workflow needs it before anything is installed, and reading the
5
+ literal avoids importing torch just to learn a version string.
6
+ """
7
+ import pathlib
8
+ import re
9
+ import sys
10
+
11
+ INIT = pathlib.Path(__file__).resolve().parent.parent / "decision_jef" / "__init__.py"
12
+ match = re.search(r'__version__ = "([^"]+)"', INIT.read_text())
13
+ if match is None:
14
+ print(f"no __version__ in {INIT}", file=sys.stderr)
15
+ raise SystemExit(1)
16
+ print(match.group(1))
verify.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Everything that has to hold before a build. Run locally and in CI.
3
+
4
+ One script, two callers: what passes on a laptop is what gates the release.
5
+ A second copy of these checks inside a workflow file would drift from this one.
6
+
7
+ python verify.py checks the installed or source package
8
+ python verify.py --build also builds and validates the artifacts
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parent
18
+ FAILURES: list[str] = []
19
+
20
+
21
+ def check(name: str):
22
+ def deco(fn):
23
+ try:
24
+ fn()
25
+ except Exception as exc: # noqa: BLE001
26
+ FAILURES.append(f"{name}: {type(exc).__name__}: {exc}")
27
+ print(f" FAIL {name}: {exc}")
28
+ else:
29
+ print(f" ok {name}")
30
+ return fn
31
+ return deco
32
+
33
+
34
+ def main() -> int:
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--build", action="store_true",
37
+ help="also build sdist and wheel and run twine check")
38
+ args = ap.parse_args()
39
+
40
+ import decision_jef
41
+ from decision_jef import Answer, Decider, Question, Request
42
+ from decision_jef.model import temperature_bucket
43
+
44
+ print(f"decision_jef {decision_jef.__version__} from "
45
+ f"{Path(decision_jef.__file__).parent}")
46
+ print("\npublic API")
47
+
48
+ @check("version is a three-part string")
49
+ def _():
50
+ parts = decision_jef.__version__.split(".")
51
+ assert len(parts) == 3 and all(p.isdigit() for p in parts), \
52
+ decision_jef.__version__
53
+
54
+ @check("the PyPI readme carries no YAML frontmatter")
55
+ def _():
56
+ readme = ROOT / "README.md"
57
+ if not readme.exists():
58
+ return
59
+ first = readme.read_text().lstrip().splitlines()[0]
60
+ assert first != "---", \
61
+ "README.md starts with frontmatter; PyPI renders it as text"
62
+
63
+ @check("pyproject leaves the version dynamic")
64
+ def _():
65
+ pp = ROOT / "pyproject.toml"
66
+ if not pp.exists():
67
+ return # installed, no source
68
+ # A plain text scan, not tomllib: that module is 3.11+ and this check
69
+ # has to run on every Python the package claims to support.
70
+ lines = [ln.strip() for ln in pp.read_text().splitlines()]
71
+ assert 'dynamic = ["version"]' in lines, "pyproject must declare a dynamic version"
72
+ assert not any(ln.startswith("version = \"") for ln in lines), \
73
+ "pyproject pins a version; it must stay dynamic"
74
+
75
+ @check("choice keys keep their given order")
76
+ def _():
77
+ q = Question("choice", "Which team?", {"b": "B", "a": "A"})
78
+ assert q.keys == ["b", "a"], q.keys
79
+
80
+ @check("score levels are indexed from zero")
81
+ def _():
82
+ s = Question("score", "How urgent?", ["low", "mid", "high"])
83
+ assert s.keys == ["0", "1", "2"] and s.descriptions[2] == "high"
84
+
85
+ @check("noul is keyed false then true")
86
+ def _():
87
+ n = Question("noul", "Urgent?", {"true": "yes", "false": "no"})
88
+ assert n.keys == ["false", "true"] and n.descriptions == ["no", "yes"]
89
+
90
+ @check("noul without criteria still answers")
91
+ def _():
92
+ assert Question("noul", "Urgent?").descriptions == ["no", "yes"]
93
+
94
+ @check("the caps are enforced")
95
+ def _():
96
+ bad = [
97
+ lambda: Question("choice", "x", {str(i): str(i) for i in range(256)}),
98
+ lambda: Question("choice", "x", {"only": "one"}),
99
+ lambda: Question("score", "x", [str(i) for i in range(11)]),
100
+ lambda: Question("score", "x", ["only one"]),
101
+ lambda: Question("noul", "x", {"maybe": "n", "true": "y"}),
102
+ lambda: Question("nope", "x", None),
103
+ ]
104
+ for i, fn in enumerate(bad):
105
+ try:
106
+ fn()
107
+ except ValueError:
108
+ continue
109
+ raise AssertionError(f"case {i} should have raised ValueError")
110
+
111
+ @check("temperature buckets are stable")
112
+ def _():
113
+ assert temperature_bucket("noul", 2) == "noul"
114
+ assert temperature_bucket("score", 5) == "score:5"
115
+ assert temperature_bucket("choice", 3) == "choice:2-3"
116
+ assert temperature_bucket("choice", 4) == "choice:4-6"
117
+ assert temperature_bucket("choice", 20) == "choice:7+"
118
+
119
+ @check("a request round-trips through JSON unchanged")
120
+ def _():
121
+ r = Request("state", {"q": Question("choice", "x?", {"a": "A", "b": "B"}),
122
+ "s": Question("score", "y?", ["lo", "hi"])})
123
+ back = Request.from_json(r.to_json())
124
+ assert back.to_json() == r.to_json()
125
+ assert back.questions["s"].keys == ["0", "1"]
126
+
127
+ @check("a noul answer expands to a distribution")
128
+ def _():
129
+ a = Answer.from_json({"type": "noul", "noul": 0.95})
130
+ assert abs(a.p("true") - 0.95) < 1e-9
131
+ assert abs(sum(a.probabilities.values()) - 1) < 1e-9
132
+
133
+ @check("log odds clamp at the reporting floor")
134
+ def _():
135
+ a = Answer("choice", {"x": 0.0, "y": 1.0})
136
+ assert a.log_odds("x", "y") < 0 and a.log_odds("x", "y") > -20
137
+
138
+ @check("absent weights raise a message that says what to do")
139
+ def _():
140
+ try:
141
+ Decider.from_pretrained(str(ROOT / "no-such-dir"))
142
+ except FileNotFoundError as exc:
143
+ assert "model.pt" in str(exc) and "hf auth login" in str(exc)
144
+ else:
145
+ raise AssertionError("expected FileNotFoundError")
146
+
147
+ if args.build:
148
+ print("\nbuild")
149
+
150
+ @check("sdist and wheel build")
151
+ def _():
152
+ # `uv build` where available, so a uv-created virtualenv without
153
+ # pip still verifies; CI installs `build` and takes the second.
154
+ import shutil
155
+ if shutil.which("uv"):
156
+ cmd = ["uv", "build", "--out-dir", str(ROOT / "dist")]
157
+ else:
158
+ cmd = [sys.executable, "-m", "build"]
159
+ subprocess.run(cmd, cwd=ROOT, check=True, capture_output=True)
160
+
161
+ @check("twine accepts the artifacts")
162
+ def _():
163
+ dist = [p for p in sorted((ROOT / "dist").glob("*"))
164
+ if p.suffix in (".whl", ".gz")]
165
+ assert dist, "nothing in dist/"
166
+ import importlib.util
167
+ if importlib.util.find_spec("twine") is None:
168
+ raise AssertionError("twine is not installed")
169
+ subprocess.run([sys.executable, "-m", "twine", "check",
170
+ *[str(p) for p in dist]],
171
+ check=True, capture_output=True)
172
+
173
+ print()
174
+ if FAILURES:
175
+ print(f"{len(FAILURES)} check(s) failed")
176
+ return 1
177
+ print("all checks passed")
178
+ return 0
179
+
180
+
181
+ if __name__ == "__main__":
182
+ sys.exit(main())