"""Attach original source notices, reproducibility files and checksums to a local release.""" import concurrent.futures import hashlib import shutil import sys import zipfile from pathlib import Path import requests sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from themis_data.v1_common import OUT, ROOT, pointers, read_jsonl, sha, write_json from themis_data.v1_release import RELEASE EVIDENCE = { "ai2d-registry.html": "https://registry.opendata.aws/allenai-diagrams/", "clevr-grant.html": "https://cs.stanford.edu/people/jcjohns/clevr/", "ami-manual-grant.html": "https://groups.inf.ed.ac.uk/ami/download/", "esci-LICENSE": "https://raw.githubusercontent.com/amazon-science/esci-data/7916cdf6ab75a462e77f20ab40428a10923998d5/LICENSE", "paperfold-code-LICENSE": "https://raw.githubusercontent.com/Jana-Z/mentis-oculi/ac6d97acf231767f408a9e5d75515872b90190d6/LICENSE", "paperfold-data-LICENSE": "https://raw.githubusercontent.com/Jana-Z/mentis-oculi/ac6d97acf231767f408a9e5d75515872b90190d6/datasets/LICENSE", "cc-by-4.0.txt": "https://creativecommons.org/licenses/by/4.0/legalcode.txt", "cc-by-sa-4.0.txt": "https://creativecommons.org/licenses/by-sa/4.0/legalcode.txt", "cdla-permissive-1.0.txt": "https://cdla.io/permissive-1-0/", } for family in ("ai2d", "clevr", "doclaynet", "paperfold", "wanli", "openjev"): p = pointers(family)[0] EVIDENCE[family + "-pinned-README.md"] = ( f"https://huggingface.co/datasets/{p['repo']}/resolve/{p['revision']}/README.md" ) if family in ("doclaynet", "paperfold"): EVIDENCE[family + "-provenance.json"] = ( f"https://huggingface.co/datasets/{p['repo']}/resolve/{p['revision']}/provenance.json" ) def fetch(item): name, url = item dest = RELEASE / "attribution/new" / name dest.parent.mkdir(parents=True, exist_ok=True) if not dest.exists(): r = requests.get(url, timeout=45) r.raise_for_status() dest.write_bytes(r.content) return dict(file=dest.relative_to(RELEASE).as_posix(), url=url, sha256=sha(dest.read_bytes())) def main(): evidence = [] failures = [] with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: results = {pool.submit(fetch, item): item for item in EVIDENCE.items()} for future in concurrent.futures.as_completed(results): try: evidence.append(future.result()) except Exception as exc: failures.append(dict(file=results[future][0], error=str(exc))) write_json( RELEASE / "attribution/evidence.json", dict(files=sorted(evidence, key=lambda x: x["file"]), failures=failures), ) print("Evidence files", len(evidence), "failures", failures, flush=True) shutil.copytree( ROOT / "release/huggingface/themis-v0/attribution", RELEASE / "attribution/inherited-v0", dirs_exist_ok=True, ) for name in ("LICENSE.md", "ATTRIBUTION.md"): shutil.copy( ROOT / "release/huggingface/themis-v0" / name, RELEASE / "attribution/inherited-v0" / name, ) for family in ("contractnli", "ami"): z = zipfile.ZipFile(pointers(family)[0]["local_path"]) names = ( ["contract-nli/LICENSE", "contract-nli/TERMS", "contract-nli/README.md"] if family == "contractnli" else ["00README_MANUAL.txt"] ) for name in names: (RELEASE / "attribution/new" / f"{family}-{Path(name).name}").write_bytes(z.read(name)) families = {} licenses = {} source_groups = {} native_categories = {} label_counts = {} assets = {} decision_assets = {} for split in ("train", "validation", "calibration", "test"): for row in read_jsonl(OUT / f"{split}.jsonl"): m = row["metadata"] if row["input"]["images"]: decision_assets[row["id"]] = [a["sha256"] for a in row["input"]["images"]] for a in row["input"]["images"]: assets[a["sha256"]] = a f = m.get("family", "inherited_v0") source_groups.setdefault(f, {}).setdefault(split, set()).add(m["group_key"]) if f != "inherited_v0": q = row["input"]["questions"]["decision"] key = row["option_keys"][ max(range(len(row["target"])), key=row["target"].__getitem__) ] value = q["criteria"][key] if q["type"] == "choice" else key label_counts.setdefault(f, {}).setdefault(split, {}) label_counts[f][split][str(value)] = label_counts[f][split].get(str(value), 0) + 1 if f == "doclaynet": cat = m["provenance"]["doc_category"] native_categories[cat] = native_categories.get(cat, 0) + 1 families.setdefault(f, {}) families[f][split] = families[f].get(split, 0) + 1 licenses[m["license"]] = licenses.get(m["license"], 0) + 1 write_json( RELEASE / "audit/coverage.json", dict( source_groups={ f: {s: len(groups) for s, groups in values.items()} for f, values in source_groups.items() }, native_document_categories=native_categories, native_target_counts=label_counts, ), ) card_path = RELEASE / "README.md" card = card_path.read_text().replace( "native highlighted-region classification over eleven classes.", "native highlighted-region classification over eleven classes. The bounded selection in this release contains only financial-report pages, not all DocLayNet document domains.", ) card = card.replace( "AMI action/decision classification uses **summary sentences and native summary sections**", "AMI action/decision classification uses **summary sentences and native summary sections**", ) card += "\nMeasured coverage limits: new AMI training rows span only **three meeting series**; this is a small development addition, not broad meeting-domain coverage. See `audit/coverage.json` for group and target counts.\n" card += "\nThe document source uses expanded export `a023fe646d5ba2fc83fcc553f356f9bba58d06b1`, training shards 0–3, superseding the earlier research note about the old 1,000-row export. `sources.lock.json` is authoritative for this actual build.\n" card_path.write_text(card) (ROOT / "docs/HF_MULTIMODAL_DATASET_CARD_DRAFT.md").write_text(card) write_json( RELEASE / "audit/ordered-assets.json", dict( assets=assets, decision_assets=decision_assets, path_note="Paths refer to the internal curated tree. Public Parquet embeds these original bytes; use the SHA256 to join records.", ), ) write_json( RELEASE / "attribution/release-counts.json", dict(families=families, licenses=licenses) ) (RELEASE / "LICENSE.md").write_text("""# Component-specific reuse terms Themis Decision Mixture v1 is a mixed-source collection. It does not replace the original grants for text, code, labels, images, or databases. Preserve each record's provenance and terms when redistributing subsets. `other` / `mixed-source-licenses` is descriptive metadata, not a new permissive grant. Inherited v0 material retains its original Apache, MIT, BSD, ISC, GPL-tagged, Creative Commons, ODC-BY, CDLA, CC0 and Unlicense terms and source-specific notices. Ambiguous original versions are not invented. See `attribution/inherited-v0/LICENSE.md` and its source catalog. New additions: AI2D is CC BY-SA 4.0; CLEVR, AMI manual annotations and ContractNLI are CC BY 4.0; highlighted DocLayNet is CDLA-Permissive-1.0; WANLI is CC BY 4.0 and Amazon ESCI is Apache-2.0; Open-Jev's mailroom-control-v1 is CC0-1.0. Fresh paper-fold generator code/original non-ImageNet assets are Apache-2.0 under its pinned evidence; the separately shipped original benchmark dataset's CC BY 4.0 notice is also retained. No ImageNet assets are included in this family. New Themis chart images and their rule labels are CC BY 4.0, attributed to lothnic / Themis, 2026. Generation uses Matplotlib and its bundled DejaVu fonts; notices accompany this release. Share-alike and attribution obligations remain applicable to their components. This collection is not uniformly Apache licensed. Source cards and preserved grants are evidence, not independent legal clearance. No new rights are granted to source content beyond the applicable original grants. """) (RELEASE / "ATTRIBUTION.md").write_text("""# Source attribution Curated by lothnic / Themis (2026). Original creators retain credit and component terms. Counts and pinned download hashes are machine-readable in `attribution/release-counts.json` and `sources.lock.json`. | Family | Creators / source | Terms | |---|---|---| | Inherited v0 | Original authors listed in [inherited attribution](attribution/inherited-v0/ATTRIBUTION.md) | Original mixed terms | | AI2D | Allen Institute for AI; Kembhavi et al., A Diagram Is Worth A Dozen Images (2016); tasksource repackaging | CC BY-SA 4.0 | | CLEVR | Justin Johnson, Bharath Hariharan, Laurens van der Maaten, Li Fei-Fei, C. Lawrence Zitnick, Ross Girshick; Cauldron repackaging | CC BY 4.0 | | DocLayNet | IBM Research authors Pfitzmann et al.; Docling / tasksource highlighted-region repackaging | CDLA-Permissive-1.0 | | Paper folding | Jana-Z / MentisOculi; tasksource fresh procedural export | Apache-2.0 fresh generator assets; retain original dataset CC BY 4.0 notice | | ContractNLI | Yuta Koreeda and Christopher D. Manning; Hitachi / Stanford (2021) | CC BY 4.0 | | AMI | AMI Consortium; manual annotation release 1.6.2 | CC BY 4.0 | | ESCI | Amazon Science; Reddy et al., Shopping Queries Dataset (2022) | Apache-2.0 | | WANLI | Alisa Liu et al., WANLI: Worker and AI Collaboration for Natural Language Inference Dataset Creation (2022) | CC BY 4.0 | | Mailroom control | ZefanCai / Open-Jev, mailroom-control-v1 | CC0-1.0 | | Themis charts v1 | lothnic / Themis, original seeded generator (2026) | CC BY 4.0 | Every retained decision records source IDs, native split, revision, label origin and transformation metadata outside inputs. `attribution/evidence.json` records URLs and checksums for preserved source notices. Research files included under `research/` describe source-selection limitations, not a claim that all planned families were admitted. """) # Matplotlib supplies all chart graphics and bundled font assets. import importlib.metadata import matplotlib for distname in ("matplotlib", "pillow"): dist = importlib.metadata.distribution(distname) for file in dist.files: if "licenses" in str(file).casefold() or Path(file).name.casefold().startswith( ("license", "copyright") ): path = Path(dist.locate_file(file)) if path.is_file(): dest = ( RELEASE / "attribution/generator-dependencies" / distname / str(file).replace("../", "") ) dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy(path, dest) font = Path(matplotlib.get_data_path()) / "fonts/ttf/LICENSE_DEJAVU" if font.exists(): shutil.copy(font, RELEASE / "attribution/new/DejaVu-LICENSE.txt") # Self-contained source snapshot: this is data-building code, never trained weights. files = [ *ROOT.glob("src/themis_data/v1_*.py"), ROOT / "src/themis_data/filters.py", ROOT / "src/themis_data/schema.py", ROOT / "src/themis_train/codec.py", ROOT / "src/themis_train/common.py", *ROOT.glob("scripts/*v1*.py"), ROOT / "pyproject.toml", ROOT / "uv.lock", ROOT / "tests/test_v1_data.py", ] hashes = {} for path in files: relative = path.relative_to(ROOT) dest = RELEASE / "builder" / relative dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy(path, dest) hashes[str(relative)] = sha(path.read_bytes()) # Package initializers must be present for explicit reproducible imports. for package in ("themis_data", "themis_train"): (RELEASE / f"builder/src/{package}/__init__.py").write_text("") write_json(RELEASE / "audit/code-hashes.json", hashes) for name in ( "themis-v1-acquisition-recipes.md", "themis-weakness-source-followup.md", "themis-vision-source-review.md", ): dest = RELEASE / "research" / name dest.parent.mkdir(exist_ok=True) shutil.copy(ROOT / "docs/research" / name, dest) (RELEASE / "BUILD.md").write_text("""# Reproduce the local release Run these commands from the Themis repository root. A pinned v0 acquisition and the protected benchmark snapshots are prerequisites; their exact byte hashes are recorded in `audit/input-files.json`. Keep evaluation records as exclusion references only. ```sh uv sync --group train --group curation --group dev uv run python scripts/acquire_v1_sources.py uv run python scripts/acquire_v1_originals.py uv run python scripts/prepare_v1_processor.py uv run python scripts/stage_v1.py text uv run python scripts/stage_v1.py contracts uv run python scripts/stage_v1.py ami uv run python scripts/stage_v1.py esci uv run python scripts/stage_v1.py vision uv run python scripts/stage_v1.py charts PYTHONPATH=src uv run python -m themis_data.v1_build PYTHONPATH=src uv run python -m themis_data.v1_release uv run pytest tests/test_v1_data.py -q uv run python scripts/finalize_v1.py ``` `builder/` contains the exact source and environment lock. Restore it into a working repository layout with the frozen original v0 and exclusion references. Tokenizer/image configuration is included under `processor/`; no GPU or model weights are needed for curation. Candidate source streams are retained locally outside the release for resuming selection. Prepared records are under `data/curated/themis-v1` locally; public-ready Parquet is under `release/huggingface/themis-v1`. This build does not upload anything or start training. The processor cap is 1,024 visual tokens/image with proportional resize; original embedded bytes remain intact. The existing v0 training and inference loaders are text-only. They must not consume image rows until the 2B multimodal trainer is implemented. Use the decision/request schema and exact renderer included here when implementing it. """) inputfiles = [] for p in [ *ROOT.glob("data/curated/themis-v0/*.jsonl"), ROOT / "data/raw/atlanai--decision-bench/test.jsonl", ROOT / "data/raw/sysone-bench/datasets/v2/manifest.v2.1.0.jsonl", ROOT / "data/raw/LocalLLaMA--typed-decisions/all/test-00000-of-00001.parquet", ]: with p.open("rb") as f: digest = hashlib.file_digest(f, "sha256").hexdigest() inputfiles.append(dict(path=str(p.relative_to(ROOT)), sha256=digest)) write_json(RELEASE / "audit/input-files.json", inputfiles) shutil.copytree(ROOT / "data/raw/v1/processor", RELEASE / "processor", dirs_exist_ok=True) write_json( RELEASE / "audit/review-status.json", dict( automated_full_release_validation=True, independent_human_semantic_review=False, visual_reliance_model_test=False, release_status="local_curated_candidate", notes="No training, model validation scores or human review pass rate is claimed.", ), ) manifest = __import__("json").loads((RELEASE / "manifest.json").read_text()) import yaml configuration = dict( status=manifest["status"], build_executed=True, publish_executed=False, version=manifest["version"], seed=manifest["seed"], preparation=manifest["preparation"], training_targets=manifest["targets"], training_retained=manifest["train_retained"], training_shortfalls=manifest["training_shortfalls"], split_boundaries="inherited v0 unchanged; native new holdouts protected; deterministic group-derived calibration", source_lock="sources.lock.json", model_inputs=["state", "questions", "images"], binary_order=["true", "false"], document_domain="financial_reports", independent_human_semantic_review=False, ) (ROOT / "configs/curation_v1.yaml").write_text(yaml.safe_dump(configuration, sort_keys=False)) shutil.copy(ROOT / "configs/curation_v1.yaml", RELEASE / "curation_v1.yaml") report = [ "# Themis dataset v1 creation report", "", f"Status: {manifest['status']}. Automatically validated; independent human semantic review remains pending.", "", "| Split | Decisions | Vision | Requests |", "|---|---:|---:|---:|", ] for split, values in manifest["splits"].items(): report.append( f"| {split} | {values['decisions']:,} | {values['vision_decisions']:,} | {manifest['packed_requests'][split]['requests']:,} |" ) report.extend( [ "", "## New training coverage", "", "| Competency | Target | Retained |", "|---|---:|---:|", ] ) for key, target in manifest["targets"].items(): report.append(f"| {key} | {target:,} | {manifest['train_retained'][key]:,} |") report.extend( [ "", "All 54,046 inherited v0 decisions, their targets, IDs and split membership were verified unchanged.", "All original image bytes are embedded in both alternative HF views; every decision appears once per view.", "New source components, original-page parents and decoded image identities have no cross-split conflicts under the recorded identity checks.", "Five-level sentiment and credential additions remain absent. AMI expansion is small after benchmark-series exclusions, and its action/decision task covers native summary items rather than utterance-level neither labels.", "Eight focused pipeline tests passed. Automated native-label consistency and image checks do not substitute for independent semantic annotation.", "No upload or training was performed. The existing 0.8B loader is text-only; multimodal training requires the planned 2B implementation.", "", "See release/huggingface/themis-v1/README.md, manifest.json and audit/ for complete evidence.", ] ) (ROOT / "reports/v1/creation-report.md").write_text("\n".join(report) + "\n") (RELEASE / "CREATION_REPORT.md").write_text("\n".join(report) + "\n") for name in ("vision-spotcheck.jpg", "visual-spotcheck-ids.json"): source = ROOT / "reports/v1" / name if source.exists(): shutil.copy(source, RELEASE / "audit" / name) # Keep the pinned source configuration and make the preparation overrides explicit. from themis_data.v1_common import Renderer renderer = Renderer() profile = manifest["preparation"] | dict( image_processor_overrides={ "size": { "shortest_edge": manifest["preparation"]["min_pixels"], "longest_edge": manifest["preparation"]["max_pixels"], } }, codec=renderer.codec.config(), processor_configs_note="Pinned source defaults are preserved under processor/. Apply these explicit overrides when preparing images.", ) profile["codec"]["max_length"] = manifest["preparation"]["max_tokens"] write_json(RELEASE / "preparation-profile.json", profile) # This file intentionally excludes itself and is the final mutation of release contents. with (RELEASE / "checksums.sha256").open("w") as f: for p in sorted(RELEASE.rglob("*")): if not p.is_file() or p.name == "checksums.sha256": continue with p.open("rb") as stream: checksum = hashlib.file_digest(stream, "sha256").hexdigest() f.write(checksum + " " + p.relative_to(RELEASE).as_posix() + "\n") print("Finalized", RELEASE, flush=True) if __name__ == "__main__": main()