Download tools/publish_dataset.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 21.8 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/tools/publish_dataset.py
- Command line
-
hf download hf://datasets/tailot/codex-python/tools/publish_dataset.py
-
curl -L -o publish_dataset.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/tools/publish_dataset.py
21.8 kB
| """Publish this folder as the dataset on the hub, and check that it arrived. | |
| Run from inside the folder: | |
| python tools/publish_dataset.py # token taken from HF_TOKEN | |
| python tools/publish_dataset.py --token-env TOKEN # another environment variable | |
| python tools/publish_dataset.py --plan # build the card, stage, upload nothing | |
| python tools/publish_dataset.py --prune # also drop files the folder no longer holds | |
| The name follows the other topology bundles (`datasets/codex/tools/publish_dataset.py` and its | |
| siblings) and deliberately avoids `publish_to_hub.py`: that name belongs to the release builder of | |
| the multilingual track. | |
| This bundle carries no kernel. It carries one corpus of its own, the thirty pattern cases under | |
| `patterns/`, generated from the rules and the fixture beside them, and the card states their | |
| denominator rather than letting thirty rows look like a benchmark. Every number the card states | |
| (gates, tests and the files holding them, node files) is re-derived from this tree, the card | |
| sentence that states them is parsed back and compared, and no constant in this file duplicates | |
| any of them: a number can only change here by changing the code that produces it. A card that | |
| contradicts the code beside it stops the run instead of publishing. | |
| The folder README is the body of the dataset card. A short list of wording pairs turns the sentences | |
| that only make sense inside a LingoLOGOS checkout, and four sections are added for readers who met | |
| the bundle on the hub. Every pair has to match the README exactly, or the tool stops. | |
| Nothing here runs during a test, and the token is never a command line argument, only the name of an | |
| environment variable. | |
| """ | |
| import argparse | |
| import ast | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import sys | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from typing import Callable, List, Tuple, TypeVar | |
| ROOT = Path(__file__).resolve().parents[1] | |
| REPO = "tailot/codex-python" | |
| ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter") | |
| ENVELOPE_KIND = "lingologos-codex-envelope-1" | |
| IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train"} | |
| IGNORED_SUFFIXES = (".pyc", ".pyo") | |
| FRONT_MATTER = """--- | |
| language: | |
| - en | |
| tags: | |
| - code | |
| - program-synthesis | |
| - multi-agent-systems | |
| - software-engineering | |
| - static-analysis | |
| - testing | |
| - formal-verification | |
| - python | |
| pretty_name: "LingoLOGOS codex-python: a Python programming layer over the codex kernel" | |
| size_categories: | |
| - n<1K | |
| --- | |
| """ | |
| # Sentences that are true in a checkout and misleading on the hub. Each pair is (here, there), and the | |
| # first has to appear in the README of this folder. | |
| REPLACEMENTS: List[Tuple[str, str]] = [ | |
| ( | |
| "An external Python programming package and six-node topology built on top of the LingoLOGOS\n" | |
| "`codex` kernel (`datasets/codex`) without modifying `datasets/codex`. Inside this repository the\n" | |
| "folder is `datasets/codex-python`, and the executables `topology.json` names are written relative to\n" | |
| "`datasets/`, so its six instances point at `codex-python/agents/python_agent.py`.", | |
| "An external Python programming package and six-node topology built on top of the LingoLOGOS\n" | |
| "`codex` kernel, a kernel this folder neither modifies nor carries. This dataset is that folder\n" | |
| "published as it stands: the package under `lingologos_python/`, the six node folders with their grammar,\n" | |
| "ontology and seed envelope, the one executable the six roles share, the two fixtures under\n" | |
| "`fixtures/` (a small package, and the pattern laboratory the catalog is measured on), the generated\n" | |
| "cases under `patterns/`, the tests, the gate runner and the publisher, and this card in place of the\n" | |
| "folder README. The kernel is a separate dataset at\n" | |
| "https://huggingface.co/datasets/tailot/lingologos-codex, and the section\n" | |
| "\"What this bundle needs from the codex kernel\" below says how the two find each other.", | |
| ), | |
| ( | |
| "From `datasets/codex-python`:", | |
| "From the folder of this dataset, with `LINGOLOGOS_CODEX_ROOT` pointing at the folder of the kernel\n" | |
| "dataset:", | |
| ), | |
| ( | |
| "- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using\n" | |
| " `datasets/codex` as its kernel base.", | |
| "- `topology.json`, `agents/python_agent.py`, `nodes/<role>/`: external six-node topology using the\n" | |
| " `codex` kernel as its base. The six executables it names are written relative to `datasets/`, so in\n" | |
| " a standalone copy that leading name is simply the folder you are standing in.", | |
| ), | |
| ] | |
| # The one sentence of the card that states the running numbers, parsed rather than copied: the four | |
| # numbers it holds are compared with the ones re-derived from this tree, and the card keeps the | |
| # sentence with a line added about what produced it. | |
| NUMBERS_SENTENCE = re.compile( | |
| r"The gate runner is where this bundle states its numbers out loud: " | |
| r"([0-9]+) gates, ([0-9]+) tests across ([0-9]+) files,\n" | |
| r"([0-9]+) files under `nodes/`, and a kernel it does not carry\." | |
| ) | |
| NUMBERS_TAIL = ( | |
| " `tools/publish_dataset.py` re-derives every\n" | |
| "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" | |
| "beside it disagrees." | |
| ) | |
| def state_numbers(text: str, derived: Tuple[int, int, int, int]) -> str: | |
| """Check the card's number sentence against the tree, then carry it onto the card.""" | |
| match = NUMBERS_SENTENCE.search(text) | |
| if match is None: | |
| raise SystemExit( | |
| "the README no longer states its numbers in the one sentence this tool knows:\n" | |
| "The gate runner is where this bundle states its numbers out loud: ..." | |
| ) | |
| stated = tuple(int(group) for group in match.groups()) | |
| if stated != derived: | |
| raise SystemExit( | |
| "the card states %d gates, %d tests in %d files, %d node files; " | |
| "the tree holds %d gates, %d tests in %d files, %d node files" | |
| % (stated + derived) | |
| ) | |
| return text[: match.end()] + NUMBERS_TAIL + text[match.end() :] | |
| # Sections a reader who found the bundle here needs and a reader inside a checkout does not. | |
| CARD_TAIL = """ | |
| ## What this bundle needs from the codex kernel | |
| `lingologos_python` imports `lingologos_codex`, and `lingologos_python/_codex_bridge.py` resolves that | |
| import in one step: an already importable `lingologos_codex`, then the folder named by | |
| `LINGOLOGOS_CODEX_ROOT`, then a sibling `codex/` or a `datasets/codex/` among the ancestors of the | |
| package. Downloaded from here the two orders are the same folder, and the resolution is: | |
| pip install -r requirements.txt | |
| git clone https://huggingface.co/datasets/tailot/lingologos-codex | |
| LINGOLOGOS_CODEX_ROOT=/path/to/lingologos-codex python -B -m pytest -p no:cacheprovider tests -q | |
| Nothing in this bundle downloads anything at run time: the kernel is a second download you make once, | |
| and the tests fail with a named reason when it is missing rather than passing without it. The kernel | |
| never imports this folder, so the dependency has exactly one direction, and one copy of the kernel can | |
| serve any number of workspaces. | |
| ## The sixteen pattern cases | |
| `patterns/pattern_cases.jsonl` holds 16 rows, one accepted and one refused for each of the eight cards | |
| of the catalog: `case_id`, `language`, `family`, `intent_tags`, the `edits` the rule returned (the | |
| source edit and the test that locks it), the verdict the run must reach, and for a refusal the | |
| `reason_code` the rule answered with. A row is a work case in the schema the kernel dataset defines in | |
| `lingologos_codex/casecorpus.py`, so its shape is checkable without a Python file in sight. | |
| `tools/build_patterns.py` derives the rows by running each rule over `fixtures/pattern_lab/`, and | |
| `--check` re-derives them and compares the bytes: a row is never edited by hand. The same tool writes | |
| `patterns/coverage.json`, which states what the sixteen rows cover and names its own denominator, the | |
| fixture. Sixteen rows are eight cards carried end to end, not a benchmark: the fixture is small and was | |
| written for this bundle, and nothing here counts coverage of real repositories. | |
| ## Rights | |
| The dataset is published by the author of LingoLOGOS under the same account, `tailot`. The source tree | |
| is the `codex-python/` folder of https://github.com/tailot/LingoLOGOS, where the project states its own | |
| terms. Neither that repository root nor this folder carries a `LICENSE` file, so no license is claimed | |
| here beyond what the publisher states on the repository and on this dataset page; ask there before | |
| reusing the code. The fixture package under `fixtures/sample_pkg/` and the pattern laboratory under | |
| `fixtures/pattern_lab/` were written for this dataset and are not taken from a third-party project. | |
| ## Citation | |
| @misc{lingologos_codex_python, | |
| title = {LingoLOGOS codex-python: a Python programming layer over the codex kernel}, | |
| author = {{LingoLOGOS}}, | |
| year = {2026}, | |
| howpublished = {\\url{https://huggingface.co/datasets/tailot/codex-python}}, | |
| } | |
| """ | |
| def local_files() -> List[Path]: | |
| """The files of this folder, caches out. | |
| The underscore rule the other bundles use cannot be copied here. This package holds | |
| `lingologos_python/_codex_bridge.py`, a private module that resolves the kernel, and `lingologos_python/__main__.py`, | |
| the entry point of `python -m lingologos_python`: a rule that drops names starting with an underscore would | |
| upload a package that cannot import itself. Only caches and bytecode stay out. | |
| """ | |
| files: List[Path] = [] | |
| for path in ROOT.rglob("*"): | |
| if not path.is_file(): | |
| continue | |
| if any(part in IGNORED_DIRS for part in path.parts): | |
| continue | |
| if path.suffix in IGNORED_SUFFIXES: | |
| continue | |
| files.append(path) | |
| return sorted(files) | |
| def build_card(derived: Tuple[int, int, int, int]) -> str: | |
| text = (ROOT / "README.md").read_text(encoding="utf-8").replace("\r\n", "\n") | |
| text = state_numbers(text, derived) | |
| for here, there in REPLACEMENTS: | |
| if here not in text: | |
| raise SystemExit( | |
| "the README no longer holds this sentence, so the card would be wrong:\n" + here[:160] | |
| ) | |
| text = text.replace(here, there) | |
| return FRONT_MATTER + text + CARD_TAIL | |
| def count_tests() -> Tuple[int, int]: | |
| """Return the number of test functions in tests/ and the number of files holding them.""" | |
| total = 0 | |
| holders = 0 | |
| for path in sorted((ROOT / "tests").glob("*.py")): | |
| tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) | |
| found = [ | |
| node.name | |
| for node in tree.body | |
| if isinstance(node, ast.FunctionDef) and node.name.startswith("test_") | |
| ] | |
| if found: | |
| holders += 1 | |
| total += len(found) | |
| return total, holders | |
| def sha256(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| T = TypeVar("T") | |
| def with_retry(label: str, action: Callable[[], T], attempts: int = 3, pause_sec: float = 2.0) -> T: | |
| """One hub call, given three honest chances with a fixed wait between them. | |
| A flaky network is not a reason to re-run a publisher that has already | |
| proven its card against its tree. Every remote call goes through here: the | |
| same call is retried up to `attempts` times with a fixed `pause_sec` wait, | |
| and the failure of the last attempt is the failure the run reports. | |
| """ | |
| for attempt in range(1, attempts + 1): | |
| try: | |
| return action() | |
| except Exception as exc: | |
| if attempt == attempts: | |
| raise | |
| print( | |
| "%s failed (%s); retrying in %.1f seconds (attempt %d of %d)" | |
| % (label, exc, pause_sec, attempt + 1, attempts) | |
| ) | |
| time.sleep(pause_sec) | |
| raise AssertionError("unreachable") | |
| def tree_digest(files: List[Path]) -> str: | |
| """The digest the gate runner writes into its report, over the same bytes. | |
| Two implementations on purpose: the runner attests the tree it judged, the | |
| publisher attests the tree it uploads, and they must agree on one number. | |
| """ | |
| digest = hashlib.sha256() | |
| for path in sorted( | |
| (p for p in files if p.relative_to(ROOT).parts[0] != "results"), | |
| key=lambda p: p.relative_to(ROOT).as_posix(), | |
| ): | |
| digest.update(path.relative_to(ROOT).as_posix().encode("ascii") + b"\0") | |
| digest.update(path.read_bytes() + b"\0") | |
| return digest.hexdigest() | |
| def gate_verdict_line(payload: dict) -> str: | |
| """The verdict line the gate runner prints, rebuilt from the report it wrote.""" | |
| gates = payload.get("gates") or [] | |
| counts = payload.get("counts") or {} | |
| return "GATES: %s (%d gates: %d CONFIRMED, %d REJECTED, %d ABSTAIN)" % ( | |
| payload.get("verdict"), | |
| len(gates), | |
| counts.get("CONFIRMED", 0), | |
| counts.get("REJECTED", 0), | |
| counts.get("ABSTAIN", 0), | |
| ) | |
| def check_gates_report() -> int: | |
| """The committed gate report has to agree with what this folder claims.""" | |
| payload = json.loads((ROOT / "results" / "gates.json").read_text(encoding="utf-8")) | |
| if payload.get("verdict") != "CONFIRMED": | |
| raise SystemExit(f"results/gates.json holds verdict '{payload.get('verdict')}'") | |
| gates = payload.get("gates") or [] | |
| if any(g.get("verdict") != "CONFIRMED" for g in gates): | |
| raise SystemExit("results/gates.json holds a gate that is not CONFIRMED") | |
| if sum((payload.get("counts") or {}).values()) != len(gates): | |
| raise SystemExit("results/gates.json counts do not add up to the gates it lists") | |
| readme = (ROOT / "README.md").read_text(encoding="utf-8") | |
| line = gate_verdict_line(payload) | |
| if line not in readme: | |
| raise SystemExit(f"the README no longer prints the verdict line the report gives: {line}") | |
| stated = payload.get("sources_sha256") | |
| current = tree_digest(local_files()) | |
| if stated != current: | |
| raise SystemExit( | |
| "results/gates.json describes a different revision of this tree (report %s, tree %s): " | |
| "rerun python -B tools/run_gates.py --report results/gates.json" | |
| % (str(stated)[:12], current[:12]) | |
| ) | |
| return len(gates) | |
| def check_topology_and_nodes() -> int: | |
| """Six roles in the topology, six node folders of three files each, ASCII everywhere.""" | |
| topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8")) | |
| if sorted(inst["id"] for inst in topo.get("instances", [])) != sorted(ROLES): | |
| raise SystemExit("topology.json does not name exactly the six codex roles") | |
| for inst in topo.get("instances", []): | |
| if not str(inst.get("executable", "")).startswith("codex-python/"): | |
| raise SystemExit(f"topology.json executable '{inst.get('executable')}' is not folder relative") | |
| if len(topo.get("routingMatrix", [])) != 6: | |
| raise SystemExit("topology.json routing matrix does not hold six rows") | |
| node_files = [p for role in ROLES for p in (ROOT / "nodes" / role).glob("*") if p.is_file()] | |
| if len(node_files) < len(ROLES) * 3: | |
| raise SystemExit(f"nodes/ holds {len(node_files)} files, fewer than three per role") | |
| for role in ROLES: | |
| for name in ("grammar.gf", "ontology.smt2", "seed_payload.json"): | |
| if not (ROOT / "nodes" / role / name).is_file(): | |
| raise SystemExit(f"nodes/{role}/{name} is missing") | |
| seed = json.loads((ROOT / "nodes" / role / "seed_payload.json").read_text(encoding="utf-8")) | |
| if seed.get("kind") != ENVELOPE_KIND or seed.get("sender") != role: | |
| raise SystemExit(f"nodes/{role}/seed_payload.json is not an envelope of this role") | |
| dossier = json.loads(seed["payload"]["abstractSyntaxTree"]) | |
| if "typecheck" not in dossier.get("required_gates", []) or "tests" not in dossier.get( | |
| "required_gates", [] | |
| ): | |
| raise SystemExit(f"nodes/{role}/seed_payload.json requires no gates") | |
| if (ROOT / "lingologos_codex").exists(): | |
| raise SystemExit("the kernel must not be vendored here: lingologos_codex/ is present in this folder") | |
| offenders = [] | |
| for path in local_files(): | |
| try: | |
| path.read_bytes().decode("ascii") | |
| except UnicodeDecodeError: | |
| offenders.append(str(path.relative_to(ROOT))) | |
| if offenders: | |
| raise SystemExit(f"non-ASCII text in {offenders}: this repository keeps every byte of prose ASCII") | |
| return len(node_files) | |
| def main(argv: List[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--repo", default=REPO) | |
| parser.add_argument("--token-env", default="HF_TOKEN") | |
| parser.add_argument("--plan", action="store_true", help="build the card and stage, upload nothing") | |
| parser.add_argument( | |
| "--prune", | |
| action="store_true", | |
| help="delete remote files the folder no longer holds instead of leaving them beside the new ones", | |
| ) | |
| args = parser.parse_args(argv) | |
| readme = (ROOT / "README.md").read_text(encoding="utf-8") | |
| notes = [word for word in ("TODO", "FIXME", "lorem") if word.lower() in readme.lower()] | |
| if notes: | |
| raise SystemExit(f"README.md still holds working notes: {notes}") | |
| gate_count = check_gates_report() | |
| node_files = check_topology_and_nodes() | |
| tests, holders = count_tests() | |
| derived = (gate_count, tests, holders, node_files) | |
| staging = Path(tempfile.mkdtemp(prefix="publish-codex-python-")) | |
| try: | |
| files = local_files() | |
| for path in files: | |
| target = staging / path.relative_to(ROOT) | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(path, target) | |
| (staging / "README.md").write_text(build_card(derived), encoding="utf-8") | |
| sources = sorted(p for p in staging.rglob("*.py")) | |
| for path in sources: | |
| compile(path.read_text(encoding="utf-8"), str(path), "exec") | |
| executable = staging / "agents" / "python_agent.py" | |
| if not executable.is_file(): | |
| raise SystemExit("the staged tree is missing agents/python_agent.py") | |
| print( | |
| f"{gate_count} gates CONFIRMED, {tests} tests in {holders} files, " | |
| f"{node_files} node files" | |
| ) | |
| print(f"staged tree: {len(files)} files, sources compiled: {len(sources)}") | |
| if args.plan: | |
| print(f"card: {(staging / 'README.md').stat().st_size} bytes, nothing uploaded") | |
| return 0 | |
| token = os.environ.get(args.token_env, "") | |
| if not token: | |
| raise SystemExit(f"no token: set {args.token_env}, or pass --token-env NAME") | |
| from huggingface_hub import HfApi, hf_hub_download # noqa: E402 (only needed to publish) | |
| api = HfApi(token=token) | |
| who = with_retry("token check", api.whoami) | |
| auth = who.get("auth") or {} | |
| if isinstance(auth, dict) and str(auth.get("role", "")) == "read": | |
| print("note: this token is read only, it cannot write a dataset") | |
| print(f"token belongs to {who.get('name')}") | |
| with_retry("create repo", lambda: api.create_repo(args.repo, repo_type="dataset", exist_ok=True)) | |
| with_retry("upload folder", lambda: api.upload_folder(folder_path=str(staging), repo_id=args.repo, repo_type="dataset")) | |
| remote = with_retry("file listing", lambda: api.list_repo_files(args.repo, repo_type="dataset")) | |
| expected = {str(p.relative_to(ROOT)).replace("\\", "/") for p in files} | |
| missing = sorted(expected - set(remote)) | |
| extra = sorted(set(remote) - expected - {".gitattributes"}) | |
| differ: List[str] = [] | |
| for name in sorted(expected & set(remote)): | |
| local = sha256((staging / name).read_bytes()) | |
| # hf_hub_download hands back a path, not the bytes, and the cached copy is read from there. | |
| fetched = with_retry("download " + name, lambda: hf_hub_download(args.repo, name, repo_type="dataset")) | |
| hub = sha256(Path(fetched).read_bytes()) | |
| if local != hub: | |
| differ.append(name) | |
| print(f"{len(remote)} objects on the hub, expected {len(files) + 1}, missing {missing}") | |
| print(f"extra {extra}, content differs {differ}") | |
| if args.prune and extra: | |
| print("pruning files the folder no longer holds") | |
| with_retry( | |
| "file removal", | |
| lambda: api.delete_files( | |
| repo_id=args.repo, | |
| repo_type="dataset", | |
| delete_patterns=extra, | |
| commit_message="drop removed files", | |
| ), | |
| ) | |
| remote = with_retry("file listing", lambda: api.list_repo_files(args.repo, repo_type="dataset")) | |
| missing = sorted(expected - set(remote)) | |
| extra = sorted(set(remote) - expected - {".gitattributes"}) | |
| print( | |
| "after the removal: %d objects, missing %d, unexpected %d" | |
| % (len(remote), len(missing), len(extra)) | |
| ) | |
| finally: | |
| shutil.rmtree(staging, ignore_errors=True) | |
| ok = (len(remote) == len(files) + 1 and not missing and not extra and not differ) | |
| print("RESULT: %s" % ("ok" if ok else "check the numbers above")) | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |