File size: 4,921 Bytes
ff0ca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the deliberately source-free public toolkit release."""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path


SPLITS = ("train", "validation", "test")
REQUIRED_FILES = (
    "README.md",
    "LICENSE",
    "NOTICE.md",
    "metrics/private_release_summary.json",
    "schemas/chat-example.schema.json",
    "docs/methodology.md",
    "docs/private-source-boundary.md",
    "docs/validation-summary.md",
)
PROHIBITED_SUFFIXES = {
    ".zip",
    ".gml",
    ".png",
    ".jpg",
    ".jpeg",
    ".gif",
    ".webp",
    ".wav",
    ".ogg",
    ".mp3",
    ".flac",
}
PROHIBITED_DATA_FIELDS = {"raw_excerpt", "source_text", "image_bytes", "audio_bytes"}
EXPECTED_ROLES = ("system", "user", "assistant")


def normalized_digest(value: object) -> str:
    encoded = json.dumps(value, ensure_ascii=False, sort_keys=True)
    normalized = " ".join(encoded.lower().split())
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()


def load_jsonl(path: Path) -> list[dict]:
    rows: list[dict] = []
    with path.open(encoding="utf-8-sig") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ValueError(f"{path}:{line_number}: invalid JSON: {exc}") from exc
            if not isinstance(row, dict):
                raise ValueError(f"{path}:{line_number}: row must be an object")
            rows.append(row)
    if not rows:
        raise ValueError(f"{path}: split is empty")
    return rows


def validate_row(path: Path, index: int, row: dict) -> None:
    label = f"{path}:{index}"
    if row.get("synthetic") is not True:
        raise ValueError(f"{label}: every public row must be explicitly synthetic")
    if not isinstance(row.get("id"), str) or not row["id"].strip():
        raise ValueError(f"{label}: missing id")
    if not isinstance(row.get("task"), str) or not row["task"].strip():
        raise ValueError(f"{label}: missing task")
    if PROHIBITED_DATA_FIELDS.intersection(row):
        raise ValueError(f"{label}: contains a prohibited private-source field")

    messages = row.get("messages")
    if not isinstance(messages, list) or len(messages) != len(EXPECTED_ROLES):
        raise ValueError(f"{label}: messages must contain system, user, and assistant")
    roles = tuple(message.get("role") for message in messages if isinstance(message, dict))
    if roles != EXPECTED_ROLES:
        raise ValueError(f"{label}: unexpected role sequence {roles}")
    for message in messages:
        if not isinstance(message.get("content"), str) or not message["content"].strip():
            raise ValueError(f"{label}: message content must be non-empty text")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    args = parser.parse_args()
    root = args.root.resolve()

    errors: list[str] = []
    for relative in REQUIRED_FILES:
        if not (root / relative).is_file():
            errors.append(f"missing required file: {relative}")

    prohibited = [
        path.relative_to(root).as_posix()
        for path in root.rglob("*")
        if path.is_file() and path.suffix.lower() in PROHIBITED_SUFFIXES
    ]
    if prohibited:
        errors.append("prohibited extracted/binary files: " + ", ".join(prohibited[:10]))

    seen_ids: set[str] = set()
    fingerprints: dict[str, str] = {}
    counts: dict[str, int] = {}
    for split in SPLITS:
        path = root / "data" / "synthetic" / f"{split}.jsonl"
        try:
            rows = load_jsonl(path)
            counts[split] = len(rows)
            for index, row in enumerate(rows, 1):
                validate_row(path.relative_to(root), index, row)
                row_id = row["id"]
                if row_id in seen_ids:
                    raise ValueError(f"duplicate id: {row_id}")
                seen_ids.add(row_id)
                fingerprint = normalized_digest(row["messages"])
                if fingerprint in fingerprints:
                    raise ValueError(
                        f"cross-split duplicate: {row_id} matches {fingerprints[fingerprint]}"
                    )
                fingerprints[fingerprint] = row_id
        except (OSError, ValueError) as exc:
            errors.append(str(exc))

    if errors:
        print("PUBLIC_RELEASE_VALIDATION=FAIL")
        for error in errors:
            print(f"- {error}")
        return 1

    print("PUBLIC_RELEASE_VALIDATION=PASS")
    print("synthetic_rows=" + str(sum(counts.values())))
    print("split_counts=" + json.dumps(counts, sort_keys=True))
    print("prohibited_files=0")
    return 0


if __name__ == "__main__":
    sys.exit(main())