Data-Lab / workflows /preprocess_text.py
KrazyKitty's picture
Create DATA LAB private review package
a490f0e verified
Raw History Blame Contribute Delete
7.16 kB
"""Run a deterministic, approval-gated reference text preprocessing experiment.
This tool is not a privacy scrubber, rights evaluator, or dataset release mechanism. It processes
only UTF-8 files explicitly named in an approved DATA LAB source manifest.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import tempfile
import unicodedata
from pathlib import Path
from 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())