File size: 7,163 Bytes
a490f0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""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())