math-stratum / tools /publish_dataset.py
tailot's picture
publish math-stratum bundle
e9dac18 verified
Raw History Blame Contribute Delete
18.2 kB
"""Publish this folder as a 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, upload nothing
python tools/publish_dataset.py --prune # also drop files the folder no longer holds
The folder README is the body of the dataset card. It is copied with its section numbers intact, and
four passages are rewritten because they only make sense inside a LingoLOGOS checkout: where the folder
sits, that it needs the sibling `math` folder, how long the suite took and what section 10 says about
this publication. Every replacement has to match, or the tool stops: a silent miss would publish a card
that contradicts the code next to it. Four sections (11 to 14) are then added for readers who met the
bundle on the hub: the fields of the corpus file, how to load it, rights, and citation. This is where
the documentation of the published asset lives, and not in the technical documentation of the project.
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 hashlib
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import List, Tuple
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from lgstratum import corpus # noqa: E402 (after the path fix above)
REPO = "tailot/math-stratum"
EXPECTED_FILES = 67 # the staged tree: this README is uploaded as the card under the same name
EXPECTED_HUB_OBJECTS = 68 # staged tree plus the .gitattributes the hub adds by itself
EXPECTED_CORPUS_ROWS = 73
IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git"}
FRONT_MATTER = """---
language:
- it
- en
- es
- zh
- hi
- ar
tags:
- multilingual
- mathematical-word-problems
- natural-language-to-formal-language
- multi-agent-systems
- benchmark
- conversational-interfaces
- formal-verification
- semantic-parsing
pretty_name: "LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading"
configs:
- config_name: corpus
data_files:
- split: train
path: problems/corpus.jsonl
size_categories:
- n<1K
---
"""
# Passages 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]] = [
(
"The folder is `datasets/math-stratum`; every command below is written from inside it and needs the\n"
"sibling folder `datasets/math`, which stays exactly as it is. Only the standard library and\n"
"`z3-solver` are required; the tests need `pytest`.",
"This dataset is the `math-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,\n"
"code and data together, plus this card in place of their README. Only the standard library and\n"
"`z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every\n"
"command below is written from inside the folder. The mathematics is not part of this dataset: it lives\n"
"in the `math` bundle, published at https://huggingface.co/datasets/tailot/lingologos-math, and section\n"
"10 says how to point this folder at a copy of it.",
),
(
"## 10. Using this folder as an external dataset",
"## 10. Putting this dataset back into a LingoLOGOS checkout",
),
(
"The split is published: https://huggingface.co/datasets/tailot/math-stratum. The published snapshot is\n"
"this content: 67 files (plus the card that replaces this README on the hub), 73 questions in one corpus\n"
"file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n"
"corpus grading and fault results under `results/`, and the fault catalogue of section 6.",
"This dataset is 67 files plus this card: 73 questions in one corpus file, the six lexicons, the eight\n"
"node definitions, the two readers, the decision rule of section 1, the corpus grading and fault results\n"
"under `results/`, and the fault catalogue of section 6. To run the mathematics it needs the `math`\n"
"bundle: download https://huggingface.co/datasets/tailot/lingologos-math somewhere, set\n"
"`LGSTRATUM_MATH_ROOT` to that copy, and the `invoker` node calls `tools/solve.py` there as a separate\n"
"process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS\n"
"checkout the folder sits at `datasets/math-stratum`, finds `datasets/math` by itself, and needs\n"
"`src/lingologos_orchestrator` importable for the two end to end sessions of section 8.",
),
(
"invariant tests call the solver of the math stratum as subprocesses, and the whole suite took 3 minutes\n"
"52 seconds on this checkout.",
"invariant tests call the solver of the math stratum as subprocesses, which here means a copy of the\n"
"`math` dataset named by `LGSTRATUM_MATH_ROOT` (section 10); the suite took 3 minutes 52 seconds inside a\n"
"LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is\n"
"not importable.",
),
(
"Like the `math` folder, this folder is ignored by the git\nrepository of the project: what the project carries is the link in the table of published resources at\nthe top of the repository README, and the documentation of the asset lives in this README and in the\ncard, not in `doc/TECHNICAL_DOCUMENTATION.md`.",
"What the LingoLOGOS repository carries is the link to this\ndataset in the table of published resources at the top of its README; the documentation of the asset\nlives here, in this card, and not in the technical documentation of the project. `tools/publish_dataset.py`\nin the folder of the project republishes a changed working copy with the token taken from an environment\nvariable.",
),
]
CARD_TAIL = """
## 11. The corpus file
`problems/corpus.jsonl` holds 73 questions, one JSON object per line, written and checked by a person.
It is a benchmark for the stratum: there is no prompt, no response pair and nothing to fine tune on.
Each row says what the session has to end like, including the rows whose expected outcome is a refusal
to answer, and a `why` that says why.
| Field | Type | Meaning |
|---|---|---|
| `id` | string | unique; the prefix names the variety (`it`, `en`, `es`, `zh`, `hi`, `ar`), or `mixed` on the 5 rows that mix varieties, write digits in full width form or are gibberish |
| `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in |
| `kind` | string | one of the 12 problem kinds, or `negative` (14 rows that must not be read) or `passthrough` (2 rows already written in the math language) |
| `question` | string | the question, between 5 and 53 characters, in the script of its variety |
| `why` | string | the reason the row behaves as it does, written by the person who wrote the row |
| `expect` | object | the expectation, described below |
| Variety (`lang`) | Rows | Id prefix | Rows | Kind | Rows |
|---|---|---|---|---|---|
| `it` | 13 | `it` | 13 | `evaluate` | 7 |
| `en` | 13 | `en` | 12 | `solve` | 6 |
| `es` | 10 | `es` | 9 | `solvez` | 3 |
| `zh` | 12 | `zh` | 11 | `prove` | 5 |
| `hi` | 12 | `hi` | 11 | `provez` | 8 |
| `ar` | 13 | `ar` | 12 | `derivative` | 4 |
| mixed rows | 5 | `mixed` | 5 | `integral` | 5 |
| | | | | `det`, `rank` | 3, 3 |
| | | | | `inverse` | 4 |
| | | | | `maximize`, `minimize` | 3, 6 |
| | | | | `negative` | 14 |
| | | | | `passthrough` | 2 |
The fields of `expect` are optional except `referee_clean`, which is present on every row.
| Field | Rows | Meaning |
|---|---|---|
| `state` | 65 | the reading state the session must end in: `AGREED` 55, `PASSTHROUGH` 3, `SINGLE` 2, `NOT COVERED` 5 |
| `sentence` | 60 | the sentence of the math language both readers have to produce, exactly |
| `answer_contains` | 29 | a substring the answer has to contain, exact rationals written as strings |
| `min_assurance` | 51 | the lowest assurance that is acceptable, on the scale of section 1 |
| `max_assurance` | 22 | the highest assurance that is acceptable: this is what pins the probes that must not rise |
| `no_answer` | 15 | `true` where the row is graded by the refusal: no answer may be shown at all |
| `referee_clean` | 73 | every envelope claim of the session must match what the referee of its node recomputed |
The eight rows with no `state` are graded on an assurance or on an answer instead: they check that the
reading holds while the math stratum abstains, so the assurance must be 0 and no answer may appear.
Seven of them are the agreed readings on which the mathematics is out of reach (`it-13`, `en-11`,
`en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`), which is the stratum refusing to add an availability it
does not have.
## 12. Loading it
Load the file with the `datasets` library, or with one `json.loads` per line, which needs no
dependency:
```python
from datasets import load_dataset
rows = load_dataset("tailot/math-stratum", "corpus", split="train")
print(rows[0])
```
This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus
`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 73 of 73
rows agree with what they expect.
## 13. Rights
No license is declared for this dataset, its lexicons, its corpus or its code: reuse is not granted by
this page. The six lexicons, the 73 questions with their gold expectations, the grammar specifications,
the node data and the Python sources were written by hand as part of the LingoLOGOS project. Ask before
redistributing or building on them, and expect the answer to be yes for academic work with attribution.
Z3 is a separate product with its own license and is not redistributed here; `z3-solver` is only named
as a dependency in `requirements.txt`. The lexicons of Hindi, Arabic and Chinese describe written
varieties as this project needs them for arithmetic questions: they are not a general purpose
dictionary of those languages.
## 14. Citation
```
@misc{lingologos_math_stratum,
title = {LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading},
author = {LingoLOGOS project},
year = {2026},
url = {https://huggingface.co/datasets/tailot/math-stratum},
note = {bundle of the math-stratum folder of the LingoLOGOS repository: 73 questions in six written
varieties, six lexicons, two independent readers, eight node definitions with SMT claims, the
assurance rule min(math, reading) with the reading capped at 2, fault catalogue and ablation
over the node configurations, 290 tests}
}
```
"""
def local_files() -> List[Path]:
"""The files of this folder that go to the hub, caches and inner git history excluded.
Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is
what keeps the compiled copies of the modules out of the published tree. A file whose own name
starts with an underscore is working notes and is not published either, with one exception:
`lgstratum/__init__.py`, the package marker, shares that prefix by the convention of Python rather
than by being a note, and dropping it would publish a tree whose library cannot be imported as a
package. A file named `.gitignore` is content for the same reason.
"""
out: List[Path] = []
for path in sorted(ROOT.rglob("*")):
if not path.is_file():
continue
relative = path.relative_to(ROOT)
if IGNORED_DIRS & set(relative.parts):
continue
if ".git" in relative.parts:
continue
if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "lgstratum"):
continue
out.append(path)
return out
def build_card() -> str:
"""The README of this folder with the checkout-only passages rewritten for the hub."""
text = (ROOT / "README.md").read_text(encoding="utf-8").replace("\r\n", "\n")
for here, there in REPLACEMENTS:
if here not in text:
raise SystemExit("card replacement not found in README.md: %r" % here[:70])
text = text.replace(here, there, 1)
return FRONT_MATTER + text.rstrip() + "\n" + CARD_TAIL
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as handle:
for block in iter(lambda: handle.read(65536), b""):
digest.update(block)
return digest.hexdigest()
def stage(card: str) -> Path:
"""A copy of the tree to upload, with the README replaced by the card.
The tree that lands on the hub has the same number of files as this folder does, because the card
replaces this README instead of being added to it; the hub adds its own `.gitattributes`, which is
why the remote count is one above the number of staged files.
"""
staging = Path(tempfile.mkdtemp(prefix="lingologos_math_stratum_"))
for path in local_files():
target = staging / path.relative_to(ROOT)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, target)
(staging / "README.md").write_text(card, encoding="utf-8", newline="\n")
return staging
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--repo", default=REPO)
parser.add_argument("--token-env", default="HF_TOKEN", help="environment variable holding the token")
parser.add_argument("--message", default="update math-stratum bundle", help="commit message, five words or fewer")
parser.add_argument("--plan", action="store_true", help="build the card and report, upload nothing")
parser.add_argument("--prune", action="store_true",
help="also delete hub files that this folder no longer holds")
args = parser.parse_args()
files = local_files()
rows = len(corpus.load(str(ROOT / "problems" / "corpus.jsonl")))
print("files that will be uploaded: %d (this README is uploaded as the card)" % len(files))
print("corpus rows: %d" % rows)
if (len(files), rows) != (EXPECTED_FILES, EXPECTED_CORPUS_ROWS):
print("UNEXPECTED: expected %d files and %d rows" % (EXPECTED_FILES, EXPECTED_CORPUS_ROWS))
return 1
card = build_card()
print("card: %d bytes" % len(card.encode("utf-8")))
if args.plan:
preview = Path(tempfile.gettempdir()) / "lingologos_math_stratum_card.md"
preview.write_text(card, encoding="utf-8", newline="\n")
print("card written to %s, nothing uploaded" % preview)
return 0
token = os.environ.get(args.token_env, "")
if not token:
print("no token in %s" % args.token_env)
return 1
from huggingface_hub import HfApi
api = HfApi(token=token)
who = api.whoami(token)
print("uploading as %s" % who.get("name", "?"))
staging = stage(card)
staging_card = Path(staging) / "README.md"
remote: List[str] = []
missing: List[str] = []
extra: List[str] = []
differ: List[str] = []
try:
api.upload_folder(
repo_id=args.repo,
repo_type="dataset",
folder_path=str(staging),
commit_message=args.message,
)
remote = api.list_repo_files(args.repo, repo_type="dataset")
print("objects on the hub: %d" % len(remote))
expected_names = {str(path.relative_to(ROOT)).replace("\\", "/") for path in files}
missing = sorted(expected_names - set(remote))
extra = sorted(set(remote) - expected_names - {".gitattributes"})
print("missing: %d %s" % (len(missing), missing[:6]))
print("unexpected: %d %s" % (len(extra), extra[:6]))
cache = tempfile.mkdtemp(prefix="lingologos_math_stratum_check_")
for path in files:
relative = str(path.relative_to(ROOT)).replace("\\", "/")
# The staged copy of the README is the card, so it is compared against what was just uploaded:
# a silent skip would leave the most read file of the dataset unverified.
local = staging_card if relative == "README.md" else path
downloaded = api.hf_hub_download(args.repo, filename=relative, repo_type="dataset", cache_dir=cache)
if sha256(Path(downloaded)) != sha256(local):
differ.append(relative)
shutil.rmtree(cache, ignore_errors=True)
print("files compared by sha256: %d (the card among them: 1), differing: %d %s"
% (len(files), len(differ), differ[:6]))
if extra and args.prune:
api.delete_files(repo_id=args.repo, repo_type="dataset", delete_patterns=extra,
commit_message="drop removed files")
remote = api.list_repo_files(args.repo, repo_type="dataset")
expected_names = {str(path.relative_to(ROOT)).replace("\\", "/") for path in files}
missing = sorted(expected_names - set(remote))
extra = sorted(set(remote) - expected_names - {".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) == EXPECTED_HUB_OBJECTS and not missing and not extra and not differ)
print("RESULT: %s" % ("ok" if ok else "check the numbers above"))
print("https://huggingface.co/datasets/%s" % args.repo)
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())