Create DATA LAB private review package
Browse filesFiles changed (13)
- README.mdAdded+86
- docs/DATA_QUALITY.mdAdded+29
- docs/EVALUATION.mdAdded+33
- docs/LICENSE_PRIVACY_CONSENT.mdAdded+44
- docs/PROVENANCE.mdAdded+52
- experiments/README.mdAdded+19
- schemas/source-manifest.schema.jsonAdded+86
- templates/dataset-card-template.mdAdded+74
- templates/evaluation-card-template.mdAdded+45
- templates/source-manifest-template.jsonAdded+42
- tests/test_workflows.pyAdded+112
- workflows/preprocess_text.pyAdded+200
- workflows/validate_manifest.pyAdded+189
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586---license: apache-2.0pretty_name: KRAZYKITTY // DATA LABtags:- data-provenance- dataset-documentation- preprocessing- data-quality- evaluation- privacy- reproducibility---
# KRAZYKITTY // DATA LAB
**Status: research documentation and workflow toolkit — no dataset is published here.**
DATA LAB is KrazyKitty's evidence-first workspace for studying how datasets should be sourced,reviewed, transformed, documented, and evaluated before they are allowed near a training orbenchmark pipeline.
This repository contains dataset-card templates, provenance schemas, deterministic preprocessingtools, evaluation guidance, and review gates. It does **not** contain a corpus, benchmark examples,training rows, scraped content, or a claim that any source is approved for KittyLM.
## Research tracks
| Track | Purpose | Current state ||---|---|---|| Source provenance | Bind each source to identity, version, integrity, licence, and allowed use | Working templates and validator || Licensing, privacy, consent | Require explicit permission and data-risk review before processing | Documented gate || Preprocessing experiments | Compare deterministic text transformations without hiding exclusions | Working local reference workflow || Data quality | Measure duplication, encoding, language, structure, contamination, and coverage | Measurement plan || Evaluation resources | Version benchmark inputs and separate test integrity from model claims | Documentation and Collection candidates || Dataset cards | Make intended use, composition, limitations, and governance visible | Reusable templates |
## Repository map
- [`docs/PROVENANCE.md`](docs/PROVENANCE.md) — evidence model and source lineage- [`docs/LICENSE_PRIVACY_CONSENT.md`](docs/LICENSE_PRIVACY_CONSENT.md) — release-blocking review- [`docs/DATA_QUALITY.md`](docs/DATA_QUALITY.md) — quality dimensions and reporting rules- [`docs/EVALUATION.md`](docs/EVALUATION.md) — benchmark governance and contamination controls- [`templates/dataset-card-template.md`](templates/dataset-card-template.md) — corpus-oriented card- [`templates/evaluation-card-template.md`](templates/evaluation-card-template.md) — evaluation-set card- [`schemas/source-manifest.schema.json`](schemas/source-manifest.schema.json) — machine-readable contract- [`workflows/validate_manifest.py`](workflows/validate_manifest.py) — standard-library validator- [`workflows/preprocess_text.py`](workflows/preprocess_text.py) — deterministic, approval-gated text reference flow- [`experiments/README.md`](experiments/README.md) — experiment record contract
## Reproducible workflow
1. Create a source manifest from the schema and keep its decision `proposed`.2. Record canonical source URLs, versions, licences, redistribution terms, integrity hashes, privacy review, consent or other lawful basis, and intended use.3. Review the source outside the preprocessing program. Automated checks do not grant permission.4. Change the manifest to `approved` only after the named reviewers have approved every source.5. Run `python workflows/validate_manifest.py manifest.json`.6. Run the reference preprocessing experiment against only the files listed in that manifest.7. Store the exact command, source revision, manifest hash, environment, counts, exclusions, and output hashes in an experiment record.8. Publish data only through a separate release decision with a complete dataset card.
## Non-goals and safeguards
- Public availability is not treated as consent or permission for model training.- A licence label is not accepted without checking scope, attribution, redistribution, and downstream restrictions.- The reference preprocessing tool is not a privacy scrubber, copyright detector, toxicity classifier, or quality oracle.- Personally identifiable, sensitive, confidential, or revoked material is release-blocking until reviewed and resolved.- Benchmark test content must not enter training mixtures.- Raw and processed data remain outside this repository unless a later, separately approved dataset release explicitly permits them.
## Relationship to KittyLM
DATA LAB can produce reviewed methods and provenance records that KittyLM may use in the future.It does not imply that KittyLM has an approved training dataset, completed data pipeline, orpublished model weights.
## Licence
The documentation, schemas, and original workflow code in this repository are proposed for releaseunder Apache-2.0. That licence does not apply to any third-party source described by a manifest.Every source retains its own rights and restrictions.1234567891011121314151617181920212223242526272829# Data quality research plan
Quality is multidimensional and purpose-dependent. A single score must not replace the underlyingmeasurements or review decisions.
## Required dimensions
| Dimension | Example evidence | Common failure ||---|---|---|| Integrity | content digest, byte count, decode errors | silent truncation or corruption || Duplication | exact and near-duplicate rates by source and split | evaluation leakage || Structure | parse success, field completeness, document boundaries | merged or fragmented records || Language | versioned detector plus manual sample | dialect and code-switch misclassification || Content quality | transparent heuristics and rejection counts | opaque quality score || Privacy | detector results plus human review | identifiers missed by automation || Safety | category definitions, sample review, subgroup counts | context-blind filtering || Coverage | domain, time, language, geography, and format distribution | hidden sampling bias || Contamination | train/eval overlap checks and hash strategy | benchmark memorisation || Reproducibility | fixed inputs, code revision, configuration, hashes | irreproducible `latest` snapshot |
## Reporting rules
- Report absolute counts and rates.- Break results down by source and split; aggregates can hide failures.- Record every exclusion reason and overlapping filter count.- Version detectors and thresholds, and retain calibration evidence.- Use deterministic sampling for manual review and record the sampling method.- Publish known blind spots and uncertainty.- Never call a source clean, safe, representative, or unbiased without scoped evidence.123456789101112131415161718192021222324252627282930313233# Evaluation resources and benchmark governance
Evaluation data requires the same provenance discipline as training data plus stronger controlsagainst contamination and answer leakage.
## Resource record
For each benchmark or evaluation set, record:
- canonical repository, paper, version, revision, and licence;- intended task, population, language, and domain;- metric definitions, aggregation, uncertainty, and known limitations;- access or gating terms and whether examples may be redistributed;- contamination risk and separation controls;- prompt, decoding, scoring, and harness versions;- sample exclusions and failure-handling policy.
## Evaluation rules
- Keep evaluation inputs out of training and prompt-development mixtures.- Do not publish gated or leakage-sensitive examples in screenshots, logs, or documentation.- Pin benchmark revisions and harness code.- Prefer deterministic or independently auditable metrics.- Report confidence intervals or run-to-run variation when stochasticity matters.- Separate capability, safety, robustness, efficiency, and user-experience claims.- Record failures and invalid runs; never silently discard them.- Treat model-graded metrics as measurements from a named, versioned judge, not objective truth.
## Example evaluation families
The research Collections nominate real external resources for study. Inclusion in a Collection isnot permission to copy, train on, redistribute, or reveal their contents. Their current licences,gates, cards, and contamination guidance must be reviewed at the time of use.1234567891011121314151617181920212223242526272829303132333435363738394041424344# Licensing, privacy, and consent gate
This gate runs before preprocessing. Passing technical validation does not satisfy it.
## Licensing review
- Identify the actual rights holder or authorised publisher.- Save the exact licence text or canonical licence URL and reviewed version.- Separate access permission, copying, transformation, training, redistribution, and commercial-use permissions; they are not interchangeable.- Record attribution, notice, share-alike, field-of-use, and deletion obligations.- Check whether dataset terms conflict with licences embedded in individual records.- Treat missing, custom, ambiguous, or conflicting terms as `pending` or `rejected`.
## Privacy and sensitive-data review
- Determine whether records contain direct or indirect personal identifiers.- Assess sensitive categories, vulnerable populations, private communications, and location data.- Document collection context, reasonable expectations, retention, access controls, and deletion.- Use data minimisation: retain only what is necessary for the approved research purpose.- Test redaction and removal procedures, but do not treat automated detection as complete.- Keep raw review material out of public repositories and logs.
## Consent and lawful basis
Consent must be specific enough for the intended use, recorded, revocable where applicable, andseparable from mere public visibility. If another lawful basis is proposed, record the jurisdiction,scope, reasoning, reviewer, and any required impact assessment. Legal uncertainty remains a stopcondition for publication.
## Approval rule
A manifest may move to `approved` only when:
- all sources have `permission_status: approved`;- privacy review is `passed`;- consent or another documented lawful basis is non-empty;- redistribution is explicitly allowed or the outputs are configured not to redistribute source content;- a named reviewer and UTC approval timestamp are present;- unresolved notes contain no release-blocking issue.
The reference validator checks that these fields exist. It cannot determine whether the legal orethical judgment is correct.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Source provenance and lineage
Provenance is the evidence chain that explains what material was considered, where it came from,which exact version was reviewed, what permission applies, how it was transformed, and why theresult is suitable for a stated research purpose.
## Minimum source record
Every source must identify:
- a stable `source_id` and human-readable title;- canonical publisher and HTTPS location;- version, snapshot date, or immutable revision;- retrieval time and SHA-256 digest of the reviewed local artifact;- licence identifier, licence URL, and redistribution decision;- privacy and sensitive-data review state;- consent, contract, public-interest, or other applicable lawful basis;- allowed purpose, restrictions, attribution, and retention requirements;- reviewer identity, decision time, and review notes.
`unknown` and `pending` are valid research states. They are not approval states.
## Lineage record
Each preprocessing run should bind:
1. source-manifest digest;2. code repository revision;3. executable command and configuration;4. runtime and dependency versions;5. input and output digests;6. accepted, rejected, duplicate, and error counts;7. split assignment method and seed, if any;8. every filter with its version and decision rule;9. a sample-based manual review record;10. known limitations and unresolved risks.
## Versioning rules
- Never overwrite a released manifest or processed artifact in place.- Treat source changes, licence changes, filter changes, and split changes as new versions.- Prefer immutable revisions and content digests over mutable `latest` URLs.- Preserve withdrawal and correction records instead of erasing history.- Record whether downstream deletion is possible when a source is withdrawn.
## Evidence language
- **Verified** — directly observed and bound to evidence in the current review.- **Proposed** — designed or nominated but not approved or executed.- **Unknown** — required evidence is missing or cannot currently be established.- **Rejected** — reviewed and not authorised for the stated purpose.- **Withdrawn** — previously considered or approved, then removed from future use.12345678910111213141516171819# Preprocessing experiment records
No preprocessing experiment has been executed or claimed by this repository package.
A future record must use an ID such as `DATA-EXP-0001` and contain:
- question and falsifiable hypothesis;- approval state and source-manifest SHA-256;- exact source and code revisions;- command, configuration, Python/dependency versions, OS, and locale;- input/output SHA-256 values;- document, byte, character, token, duplicate, rejection, and error counts;- filter order, thresholds, versions, and exclusion reasons;- deterministic sampling and split method;- privacy/licensing reviewer and decision reference;- results, limitations, failures, and follow-up decision.
Do not edit a completed record to make a result look cleaner. Append a correction or create a newexperiment ID.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "urn:krazykitty:data-lab:source-manifest:1.0", "title": "KRAZYKITTY DATA LAB source manifest", "type": "object", "additionalProperties": false, "required": ["schema_version", "dataset_id", "decision", "sources"], "properties": { "schema_version": {"const": "1.0"}, "dataset_id": {"type": "string", "minLength": 1}, "decision": { "type": "object", "additionalProperties": false, "required": ["status", "reviewed_by", "reviewed_at", "notes"], "properties": { "status": {"enum": ["proposed", "approved", "rejected", "withdrawn"]}, "reviewed_by": {"type": ["string", "null"]}, "reviewed_at": {"type": ["string", "null"], "format": "date-time"}, "notes": {"type": "array", "items": {"type": "string"}} } }, "sources": { "type": "array", "items": { "type": "object", "additionalProperties": false, "required": [ "source_id", "title", "publisher", "canonical_url", "version", "retrieved_at", "content_path", "sha256", "license", "privacy", "use" ], "properties": { "source_id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"}, "title": {"type": "string", "minLength": 1}, "publisher": {"type": "string", "minLength": 1}, "canonical_url": {"type": "string", "format": "uri", "pattern": "^https://"}, "version": {"type": "string", "minLength": 1}, "retrieved_at": {"type": "string", "format": "date-time"}, "content_path": {"type": "string", "minLength": 1}, "sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "license": { "type": "object", "additionalProperties": false, "required": ["identifier", "url", "permission_status", "redistribution", "attribution"], "properties": { "identifier": {"type": "string", "minLength": 1}, "url": {"type": "string", "format": "uri", "pattern": "^https://"}, "permission_status": {"enum": ["pending", "approved", "rejected"]}, "redistribution": {"enum": ["allowed", "restricted", "prohibited", "unknown"]}, "attribution": {"type": "string"} } }, "privacy": { "type": "object", "additionalProperties": false, "required": ["review_status", "contains_personal_data", "consent_or_lawful_basis", "notes"], "properties": { "review_status": {"enum": ["pending", "passed", "failed"]}, "contains_personal_data": {"type": ["boolean", "null"]}, "consent_or_lawful_basis": {"type": "string"}, "notes": {"type": "array", "items": {"type": "string"}} } }, "use": { "type": "object", "additionalProperties": false, "required": ["purpose", "allowed", "restrictions"], "properties": { "purpose": {"type": "string", "minLength": 1}, "allowed": {"type": "boolean"}, "restrictions": {"type": "array", "items": {"type": "string"}} } } } } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374---license: <reviewed-spdx-identifier-or-other>pretty_name: <dataset-display-name>language:- <language-tag>tags:- <purpose-tag>---
# Dataset Card for `<dataset-id>`
> **Template only. Replace every angle-bracket field and remove this notice before release.**
## Summary
- **Version:** `<immutable-version>`- **Status:** `<proposed | approved-for-private-research | released | withdrawn>`- **Maintainer:** `<responsible-owner>`- **Canonical source manifest:** `<path-or-immutable-link-and-sha256>`- **Release decision:** `<approval-record>`
Describe what the dataset contains and what evidence supports that description. Do not promote aplanned collection or processing pipeline into a released dataset claim.
## Intended uses
### Supported
- `<specific, evidence-backed research use>`
### Out of scope
- `<use not evaluated or not permitted>`
## Source data and provenance
For every source, provide the publisher, canonical URL, version/revision, retrieval date, integritydigest, licence, permission scope, privacy review, consent or lawful basis, and transformationlineage. Link to a machine-readable manifest without exposing private paths or source content.
## Processing
Record the exact code revision, configuration, command, dependency lock, input/output hashes,filter versions, exclusion counts, deduplication method, and split assignment.
## Composition and splits
Report records, bytes, characters, tokens (with tokenizer version), languages, domains, time range,formats, source mixture, missing values, duplicates, and rejection counts for every split.
## Licensing, privacy, and consent
Explain the licence analysis, attribution, redistribution rights, privacy controls, sensitive-datareview, consent or other lawful basis, retention, withdrawal, and deletion process.
## Quality and validation
Provide scoped measurements, manual-review sampling, contamination checks, known blind spots, andunresolved issues. Avoid unsupported labels such as clean, safe, or representative.
## Limitations and risks
Document sampling bias, detector limitations, temporal limits, language/domain gaps, harmfulcontent, privacy residuals, contamination risk, and inappropriate downstream uses.
## Reproducibility
Provide immutable source, code, configuration, environment, and artifact identifiers sufficient foran authorised reviewer to reproduce the release.
## Changes and withdrawal
Maintain an append-only version history with corrections, removals, licence changes, and downstreamnotification requirements.123456789101112131415161718192021222324252627282930313233343536373839404142434445# Evaluation Resource Card for `<resource-id>`
> **Template only. This file contains no benchmark examples or answers.**
## Identity
- **Task:** `<task-definition>`- **Version/revision:** `<immutable-id>`- **Canonical repository and paper:** `<links>`- **Licence and access terms:** `<reviewed-terms>`- **Gating or leakage restrictions:** `<restrictions>`
## Population and scope
Define languages, domains, time range, difficulty, participant or source population, and what theresource does not measure.
## Protocol
Pin prompts, tools, retrieval index, system policy, model/checkpoint, tokenizer, decoding,environment, seeds, retries, timeouts, and scoring harness.
## Metrics
For every metric, define inputs, formula, aggregation, uncertainty, invalid-run handling, and theclaim it can and cannot support.
## Integrity and contamination
Document split separation, train/eval overlap checks, answer-access controls, test-set secrecy, andhow public traces or screenshots avoid revealing restricted examples.
## Limitations
Document construct validity, annotation disagreement, judge bias, saturation, temporal drift,contamination risk, subgroup gaps, and cost constraints.
## Reporting checklist
- [ ] Exact revision and harness recorded- [ ] Licence and gating terms rechecked- [ ] No restricted example or answer exposed- [ ] Invalid and failed runs counted- [ ] Confidence or run-to-run variation reported where relevant- [ ] Capability, safety, robustness, and efficiency reported separately123456789101112131415161718192021222324252627282930313233343536373839404142{ "schema_version": "1.0", "dataset_id": "<proposed-dataset-id>@<version>", "decision": { "status": "proposed", "reviewed_by": null, "reviewed_at": null, "notes": [ "Template only. This manifest does not describe or approve a real dataset." ] }, "sources": [ { "source_id": "<stable-source-id>", "title": "<source-title>", "publisher": "<publisher-or-rights-holder>", "canonical_url": "https://<canonical-source-location>", "version": "<immutable-version-or-revision>", "retrieved_at": "<UTC-RFC3339-timestamp>", "content_path": "<relative-reviewed-file-path>", "sha256": "<lowercase-sha256-of-reviewed-file>", "license": { "identifier": "<SPDX-or-reviewed-custom-identifier>", "url": "https://<canonical-licence-location>", "permission_status": "pending", "redistribution": "unknown", "attribution": "<required-attribution>" }, "privacy": { "review_status": "pending", "contains_personal_data": null, "consent_or_lawful_basis": "", "notes": [] }, "use": { "purpose": "<specific-research-purpose>", "allowed": false, "restrictions": [] } } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112from __future__ import annotations
import hashlibimport jsonimport sysimport tempfileimport unittestfrom pathlib import Path
WORKFLOWS = Path(__file__).resolve().parents[1] / "workflows"sys.path.insert(0, str(WORKFLOWS))
from preprocess_text import run_preprocessing # noqa: E402from validate_manifest import validate_manifest # noqa: E402
def approved_manifest(content: bytes) -> dict[str, object]: return { "schema_version": "1.0", "dataset_id": "synthetic-test@1", "decision": { "status": "approved", "reviewed_by": "test-reviewer", "reviewed_at": "2026-10-11T00:00:00Z", "notes": ["Synthetic unit-test fixture only."], }, "sources": [ { "source_id": "synthetic-one", "title": "Synthetic unit-test text", "publisher": "DATA LAB tests", "canonical_url": "https://example.invalid/synthetic-one", "version": "1", "retrieved_at": "2026-10-11T00:00:00Z", "content_path": "input.txt", "sha256": hashlib.sha256(content).hexdigest(), "license": { "identifier": "CC0-1.0", "url": "https://creativecommons.org/publicdomain/zero/1.0/", "permission_status": "approved", "redistribution": "allowed", "attribution": "", }, "privacy": { "review_status": "passed", "contains_personal_data": False, "consent_or_lawful_basis": "Synthetic text created by the test.", "notes": [], }, "use": { "purpose": "Workflow unit test", "allowed": True, "restrictions": [], }, } ], }
class ManifestTests(unittest.TestCase): def test_approved_manifest_is_valid(self) -> None: self.assertEqual(validate_manifest(approved_manifest(b"hello\n")), [])
def test_traversal_path_is_rejected(self) -> None: manifest = approved_manifest(b"hello\n") manifest["sources"][0]["content_path"] = "../outside.txt" # type: ignore[index] self.assertTrue(any("safe" in error for error in validate_manifest(manifest)))
def test_approval_requires_privacy_gate(self) -> None: manifest = approved_manifest(b"hello\n") manifest["sources"][0]["privacy"]["review_status"] = "pending" # type: ignore[index] self.assertTrue(any("privacy" in error for error in validate_manifest(manifest)))
class PreprocessingTests(unittest.TestCase): def test_output_is_deterministic_and_contains_no_absolute_path(self) -> None: content = "Synthetic text. \r\n\r\n\r\nSecond line.\r\n".encode() with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) input_root = root / "input" input_root.mkdir() (input_root / "input.txt").write_bytes(content) manifest_path = root / "manifest.json" manifest_path.write_text(json.dumps(approved_manifest(content)), encoding="utf-8")
report_a = run_preprocessing(manifest_path, input_root, root / "out-a") report_b = run_preprocessing(manifest_path, input_root, root / "out-b")
records_a = (root / "out-a" / "records.jsonl").read_bytes() records_b = (root / "out-b" / "records.jsonl").read_bytes() self.assertEqual(records_a, records_b) self.assertEqual(report_a, report_b) self.assertNotIn(str(root).encode(), records_a) self.assertEqual(report_a["counts"]["accepted_records"], 1)
def test_proposed_manifest_cannot_run(self) -> None: content = b"synthetic\n" with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) input_root = root / "input" input_root.mkdir() (input_root / "input.txt").write_bytes(content) manifest = approved_manifest(content) manifest["decision"]["status"] = "proposed" # type: ignore[index] manifest_path = root / "manifest.json" manifest_path.write_text(json.dumps(manifest), encoding="utf-8") with self.assertRaisesRegex(ValueError, "approved"): run_preprocessing(manifest_path, input_root, root / "out")
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Run a deterministic, approval-gated reference text preprocessing experiment.
This tool is not a privacy scrubber, rights evaluator, or dataset release mechanism. It processesonly UTF-8 files explicitly named in an approved DATA LAB source manifest."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport tempfileimport unicodedatafrom pathlib import Pathfrom typing import Any
from validate_manifest import load_manifest, validate_manifest
def sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest()
def normalize_text(text: str, unicode_form: str) -> str: text = text.replace("\r\n", "\n").replace("\r", "\n") if unicode_form != "none": text = unicodedata.normalize(unicode_form, text) lines = [line.rstrip() for line in text.split("\n")] normalized: list[str] = [] blank_count = 0 for line in lines: if line: blank_count = 0 normalized.append(line) else: blank_count += 1 if blank_count <= 2: normalized.append("") return "\n".join(normalized).strip() + "\n"
def split_for_digest(digest: str) -> str: bucket = int(digest[:8], 16) % 10_000 if bucket < 8_000: return "train" if bucket < 9_000: return "validation" return "test"
def _atomic_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( "w", encoding="utf-8", dir=path.parent, delete=False, newline="\n" ) as handle: json.dump(value, handle, ensure_ascii=False, indent=2, sort_keys=True) handle.write("\n") temporary = Path(handle.name) temporary.replace(path)
def _atomic_jsonl(path: Path, values: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( "w", encoding="utf-8", dir=path.parent, delete=False, newline="\n" ) as handle: for value in values: handle.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n") temporary = Path(handle.name) temporary.replace(path)
def run_preprocessing( manifest_path: Path, input_root: Path, output_root: Path, *, unicode_form: str = "NFC", min_characters: int = 1,) -> dict[str, Any]: manifest_path = manifest_path.resolve() input_root = input_root.resolve() output_root = output_root.resolve()
manifest = load_manifest(manifest_path) errors = validate_manifest(manifest) if errors: raise ValueError("manifest validation failed: " + "; ".join(errors)) if manifest["decision"]["status"] != "approved": raise ValueError("preprocessing requires decision.status='approved'") if output_root == input_root or output_root.is_relative_to(input_root): raise ValueError("output directory must be outside the input directory") if min_characters < 1: raise ValueError("min_characters must be at least 1")
records: list[dict[str, Any]] = [] seen_content: set[str] = set() rejected = {"duplicate": 0, "too_short": 0} source_summaries: list[dict[str, Any]] = []
for source in sorted(manifest["sources"], key=lambda item: item["source_id"]): relative_path = Path(*source["content_path"].split("/")) candidate = input_root / relative_path if candidate.is_symlink(): raise ValueError(f"symlink input is not allowed: {source['content_path']}") resolved = candidate.resolve(strict=True) if not resolved.is_relative_to(input_root): raise ValueError(f"input escapes root: {source['content_path']}") raw = resolved.read_bytes() raw_digest = sha256_bytes(raw) if raw_digest != source["sha256"]: raise ValueError(f"SHA-256 mismatch for {source['source_id']}") try: text = raw.decode("utf-8", errors="strict") except UnicodeDecodeError as exc: raise ValueError(f"UTF-8 decode failed for {source['source_id']}: {exc}") from exc
normalized = normalize_text(text, unicode_form) content_digest = sha256_bytes(normalized.encode("utf-8")) if len(normalized.strip()) < min_characters: rejected["too_short"] += 1 continue if content_digest in seen_content: rejected["duplicate"] += 1 continue seen_content.add(content_digest) record = { "id": content_digest, "source_id": source["source_id"], "split": split_for_digest(content_digest), "text": normalized, } records.append(record) source_summaries.append( { "source_id": source["source_id"], "input_sha256": raw_digest, "output_sha256": content_digest, "input_bytes": len(raw), "output_characters": len(normalized), "split": record["split"], } )
records.sort(key=lambda item: (item["source_id"], item["id"])) manifest_digest = sha256_bytes(manifest_path.read_bytes()) report = { "schema_version": "1.0", "dataset_id": manifest["dataset_id"], "manifest_sha256": manifest_digest, "settings": { "unicode_form": unicode_form, "min_characters": min_characters, "deduplication": "exact normalized UTF-8 SHA-256", "split_assignment": "SHA-256 bucket 80/10/10", }, "counts": { "manifest_sources": len(manifest["sources"]), "accepted_records": len(records), "rejected_duplicate": rejected["duplicate"], "rejected_too_short": rejected["too_short"], }, "sources": source_summaries, "warnings": [ "This reference workflow does not establish privacy, copyright, safety, or data quality." ], } output_root.mkdir(parents=True, exist_ok=True) _atomic_jsonl(output_root / "records.jsonl", records) _atomic_json(output_root / "report.json", report) return report
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest", required=True, type=Path) parser.add_argument("--input", required=True, type=Path, dest="input_root") parser.add_argument("--output", required=True, type=Path, dest="output_root") parser.add_argument("--unicode-form", choices=("none", "NFC", "NFKC"), default="NFC") parser.add_argument("--min-characters", type=int, default=1) args = parser.parse_args()
try: report = run_preprocessing( args.manifest, args.input_root, args.output_root, unicode_form=args.unicode_form, min_characters=args.min_characters, ) except (OSError, ValueError, json.JSONDecodeError) as exc: print(f"FAILED: {exc}") return 1
print(json.dumps(report["counts"], sort_keys=True)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Validate a DATA LAB source manifest without external dependencies."""
from __future__ import annotations
import argparseimport jsonimport refrom datetime import datetimefrom pathlib import Path, PurePosixPathfrom typing import Anyfrom urllib.parse import urlparse
SHA256_RE = re.compile(r"^[a-f0-9]{64}$")SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")DECISIONS = {"proposed", "approved", "rejected", "withdrawn"}PERMISSIONS = {"pending", "approved", "rejected"}REDISTRIBUTION = {"allowed", "restricted", "prohibited", "unknown"}PRIVACY_STATES = {"pending", "passed", "failed"}
def _is_https(value: Any) -> bool: if not isinstance(value, str): return False parsed = urlparse(value) return parsed.scheme == "https" and bool(parsed.netloc)
def _is_utc_timestamp(value: Any) -> bool: if not isinstance(value, str) or not value.endswith("Z"): return False try: datetime.fromisoformat(value.removesuffix("Z") + "+00:00") except ValueError: return False return True
def _is_safe_relative_path(value: Any) -> bool: if not isinstance(value, str) or not value.strip() or "\\" in value: return False path = PurePosixPath(value) return not path.is_absolute() and ".." not in path.parts and "." not in path.parts
def validate_manifest(data: Any) -> list[str]: """Return human-readable validation errors; an empty list means valid.""" errors: list[str] = [] if not isinstance(data, dict): return ["manifest root must be a JSON object"]
if data.get("schema_version") != "1.0": errors.append("schema_version must be '1.0'") if not isinstance(data.get("dataset_id"), str) or not data["dataset_id"].strip(): errors.append("dataset_id must be a non-empty string")
decision = data.get("decision") if not isinstance(decision, dict): errors.append("decision must be an object") decision = {} status = decision.get("status") if status not in DECISIONS: errors.append(f"decision.status must be one of {sorted(DECISIONS)}") if not isinstance(decision.get("notes"), list) or not all( isinstance(note, str) for note in decision.get("notes", []) ): errors.append("decision.notes must be an array of strings") if status == "approved": if not isinstance(decision.get("reviewed_by"), str) or not decision["reviewed_by"].strip(): errors.append("approved manifest requires decision.reviewed_by") if not _is_utc_timestamp(decision.get("reviewed_at")): errors.append("approved manifest requires a UTC decision.reviewed_at ending in Z")
sources = data.get("sources") if not isinstance(sources, list): errors.append("sources must be an array") return errors
seen_ids: set[str] = set() for index, source in enumerate(sources): prefix = f"sources[{index}]" if not isinstance(source, dict): errors.append(f"{prefix} must be an object") continue
source_id = source.get("source_id") if not isinstance(source_id, str) or not SOURCE_ID_RE.fullmatch(source_id): errors.append(f"{prefix}.source_id must use lowercase letters, digits, dot, underscore, or hyphen") elif source_id in seen_ids: errors.append(f"{prefix}.source_id is duplicated: {source_id}") else: seen_ids.add(source_id)
for field in ("title", "publisher", "version"): if not isinstance(source.get(field), str) or not source[field].strip(): errors.append(f"{prefix}.{field} must be a non-empty string") if not _is_https(source.get("canonical_url")): errors.append(f"{prefix}.canonical_url must be an HTTPS URL") if not _is_utc_timestamp(source.get("retrieved_at")): errors.append(f"{prefix}.retrieved_at must be a UTC timestamp ending in Z") if not _is_safe_relative_path(source.get("content_path")): errors.append(f"{prefix}.content_path must be a safe POSIX-style relative path") if not isinstance(source.get("sha256"), str) or not SHA256_RE.fullmatch(source["sha256"]): errors.append(f"{prefix}.sha256 must be a lowercase 64-character SHA-256 digest")
licence = source.get("license") if not isinstance(licence, dict): errors.append(f"{prefix}.license must be an object") licence = {} if not isinstance(licence.get("identifier"), str) or not licence["identifier"].strip(): errors.append(f"{prefix}.license.identifier must be non-empty") if not _is_https(licence.get("url")): errors.append(f"{prefix}.license.url must be an HTTPS URL") if licence.get("permission_status") not in PERMISSIONS: errors.append(f"{prefix}.license.permission_status is invalid") if licence.get("redistribution") not in REDISTRIBUTION: errors.append(f"{prefix}.license.redistribution is invalid")
privacy = source.get("privacy") if not isinstance(privacy, dict): errors.append(f"{prefix}.privacy must be an object") privacy = {} if privacy.get("review_status") not in PRIVACY_STATES: errors.append(f"{prefix}.privacy.review_status is invalid") if privacy.get("contains_personal_data") not in (True, False, None): errors.append(f"{prefix}.privacy.contains_personal_data must be true, false, or null") if not isinstance(privacy.get("notes"), list) or not all( isinstance(note, str) for note in privacy.get("notes", []) ): errors.append(f"{prefix}.privacy.notes must be an array of strings")
use = source.get("use") if not isinstance(use, dict): errors.append(f"{prefix}.use must be an object") use = {} if not isinstance(use.get("purpose"), str) or not use["purpose"].strip(): errors.append(f"{prefix}.use.purpose must be non-empty") if not isinstance(use.get("allowed"), bool): errors.append(f"{prefix}.use.allowed must be a boolean") if not isinstance(use.get("restrictions"), list) or not all( isinstance(item, str) for item in use.get("restrictions", []) ): errors.append(f"{prefix}.use.restrictions must be an array of strings")
if status == "approved": if licence.get("permission_status") != "approved": errors.append(f"{prefix} is not approved by the licensing review") if privacy.get("review_status") != "passed": errors.append(f"{prefix} has not passed privacy review") if not isinstance(privacy.get("consent_or_lawful_basis"), str) or not privacy[ "consent_or_lawful_basis" ].strip(): errors.append(f"{prefix} lacks consent or another documented lawful basis") if use.get("allowed") is not True: errors.append(f"{prefix}.use.allowed must be true for an approved manifest")
return errors
def load_manifest(path: Path) -> dict[str, Any]: data = json.loads(path.read_text(encoding="utf-8")) if not isinstance(data, dict): raise ValueError("manifest root must be an object") return data
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("manifest", type=Path) args = parser.parse_args()
try: data = load_manifest(args.manifest) except (OSError, json.JSONDecodeError, ValueError) as exc: print(f"INVALID: {exc}") return 2
errors = validate_manifest(data) if errors: print("INVALID") for error in errors: print(f"- {error}") return 1
print(f"VALID: {data['dataset_id']} ({data['decision']['status']})") return 0
if __name__ == "__main__": raise SystemExit(main())README.mdAdded+86
docs/DATA_QUALITY.mdAdded+29
docs/EVALUATION.mdAdded+33
docs/LICENSE_PRIVACY_CONSENT.mdAdded+44
docs/PROVENANCE.mdAdded+52
experiments/README.mdAdded+19
schemas/source-manifest.schema.jsonAdded+86
templates/dataset-card-template.mdAdded+74
templates/evaluation-card-template.mdAdded+45
templates/source-manifest-template.jsonAdded+42
tests/test_workflows.pyAdded+112
workflows/preprocess_text.pyAdded+200
workflows/validate_manifest.pyAdded+189