PsyAgent / scripts /prepare_dataset.py
zmengal0116's picture
Fix dataset loading and publish validation summary
f53fecc verified
Raw History Blame Contribute Delete
16.6 kB
#!/usr/bin/env python3
"""Validate the PsyAgent JSON archive and create Hugging Face Parquet files.
The source ZIP is read in place. The ZIP itself is never copied into the
publishable output directory.
"""
from __future__ import annotations
import argparse
import collections
import datetime as dt
import hashlib
import json
import re
import shutil
import sys
import zipfile
from pathlib import Path
from typing import Any, Iterable
import pyarrow as pa
import pyarrow.parquet as pq
TRAITS = (
"Openness",
"Conscientiousness",
"Extraversion",
"Agreeableness",
"Neuroticism",
)
ALLOWED_TRAIT_VALUES = {0, 20, 40, 60, 80, 100}
EXPECTED_OUTPUTS = 13
MODEL_SPECS = {
"output_llama_3_2_1B": {
"config": "llama-3.2-1b-instruct",
"model_id": "meta-llama/Llama-3.2-1B-Instruct",
},
"output_llama_3_2_3B": {
"config": "llama-3.2-3b-instruct",
"model_id": "meta-llama/Llama-3.2-3B-Instruct",
},
"output_llama_3_1_8B": {
"config": "llama-3.1-8b-instruct",
"model_id": "meta-llama/Meta-Llama-3.1-8B-Instruct",
},
}
FILE_RE = re.compile(r"^(?P<profile>\d+)_(?P<seed>\d+)\.json$")
SCAN_PATTERNS = {
"private_key": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
"huggingface_token": re.compile(r"\bhf_[A-Za-z0-9]{30,}\b"),
"openai_token": re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"),
"github_token": re.compile(r"\b(?:ghp|github_pat)_[A-Za-z0-9_]{20,}\b"),
"aws_access_key": re.compile(r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b"),
"email": re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.I),
"ipv4": re.compile(r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)"),
"local_path": re.compile(r"(?:/Users/|/home/|/scratch/|/gpfs/|[A-Z]:\\\\Users\\\\)"),
}
ARROW_SCHEMA = pa.schema(
[
pa.field("id", pa.string(), nullable=False),
pa.field("profile_id", pa.int32(), nullable=False),
pa.field("seed", pa.int16(), nullable=False),
pa.field("generator_model", pa.string(), nullable=False),
pa.field("openness", pa.int16(), nullable=False),
pa.field("conscientiousness", pa.int16(), nullable=False),
pa.field("extraversion", pa.int16(), nullable=False),
pa.field("agreeableness", pa.int16(), nullable=False),
pa.field("neuroticism", pa.int16(), nullable=False),
pa.field(
"outputs",
pa.list_(
pa.struct(
[
pa.field("name", pa.string(), nullable=False),
pa.field("content", pa.string(), nullable=False),
]
)
),
nullable=False,
),
pa.field("source_file", pa.string(), nullable=False),
]
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--archive", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--batch-size", type=int, default=256)
return parser.parse_args()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def write_rows(writer: pq.ParquetWriter, rows: list[dict[str, Any]]) -> None:
if rows:
writer.write_table(pa.Table.from_pylist(rows, schema=ARROW_SCHEMA))
rows.clear()
def normalized_digest(payload: dict[str, Any]) -> str:
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def scan_text(text: str, source: str, audit: dict[str, dict[str, Any]]) -> None:
for label, pattern in SCAN_PATTERNS.items():
count = len(pattern.findall(text))
if not count:
continue
audit[label]["matches"] += count
audit[label]["file_names"].add(source)
if source not in audit[label]["example_files"] and len(audit[label]["example_files"]) < 20:
audit[label]["example_files"].append(source)
def validate_payload(payload: Any, source: str) -> tuple[dict[str, int], list[dict[str, str]]]:
if not isinstance(payload, dict) or set(payload) != {"big5", "outputs"}:
raise ValueError(f"{source}: top-level schema is not exactly big5 + outputs")
big5 = payload["big5"]
if not isinstance(big5, dict) or set(big5) != set(TRAITS):
raise ValueError(f"{source}: invalid Big Five fields")
for trait in TRAITS:
value = big5[trait]
if isinstance(value, bool) or not isinstance(value, int) or value not in ALLOWED_TRAIT_VALUES:
raise ValueError(f"{source}: invalid {trait} value {value!r}")
outputs = payload["outputs"]
if not isinstance(outputs, list) or len(outputs) != EXPECTED_OUTPUTS:
raise ValueError(f"{source}: expected {EXPECTED_OUTPUTS} outputs")
clean_outputs: list[dict[str, str]] = []
for index, item in enumerate(outputs):
if not isinstance(item, dict) or set(item) != {"name", "content"}:
raise ValueError(f"{source}: output {index} has an invalid schema")
name = item["name"]
content = item["content"]
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{source}: output {index} has an empty name")
if not isinstance(content, str):
raise ValueError(f"{source}: output {index} content is not a string")
clean_outputs.append({"name": name, "content": content})
return {trait: int(big5[trait]) for trait in TRAITS}, clean_outputs
def batched(items: list[zipfile.ZipInfo], size: int) -> Iterable[list[zipfile.ZipInfo]]:
for index in range(0, len(items), size):
yield items[index : index + size]
def main() -> int:
args = parse_args()
archive = args.archive.resolve()
output = args.output.resolve()
if not archive.is_file():
raise FileNotFoundError(archive)
if args.batch_size < 1:
raise ValueError("batch size must be positive")
data_dir = output / "data"
report_dir = output / ".local"
if data_dir.exists():
shutil.rmtree(data_dir)
if report_dir.exists():
shutil.rmtree(report_dir)
data_dir.mkdir(parents=True, exist_ok=True)
report_dir.mkdir(parents=True, exist_ok=True)
archive_sha256 = sha256_file(archive)
report: dict[str, Any] = {
"release": "1.0",
"created_utc": dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat(),
"source_archive": archive.name,
"source_archive_size_bytes": archive.stat().st_size,
"source_archive_sha256": archive_sha256,
"source_archive_published": False,
"license": "CC BY 4.0",
"models": {},
"cross_model_checks": {},
}
mappings_by_model: dict[str, dict[int, tuple[int, ...]]] = {}
with zipfile.ZipFile(archive) as zf:
bad_member_names = [
info.filename
for info in zf.infolist()
if info.filename.startswith("/") or ".." in Path(info.filename).parts
]
if bad_member_names:
raise ValueError(f"unsafe archive member paths detected: {len(bad_member_names)}")
all_json_members = [info for info in zf.infolist() if info.filename.endswith(".json")]
recognized = set()
for source_dir, spec in MODEL_SPECS.items():
members = []
for info in all_json_members:
path = Path(info.filename)
if len(path.parts) != 2 or path.parts[0] != source_dir:
continue
match = FILE_RE.match(path.name)
if not match:
raise ValueError(f"unexpected filename in {source_dir}: {path.name}")
members.append(info)
recognized.add(info.filename)
members.sort(
key=lambda info: tuple(
int(FILE_RE.match(Path(info.filename).name).group(key))
for key in ("profile", "seed")
)
)
if not members:
raise ValueError(f"no JSON records found for {source_dir}")
config = spec["config"]
model_id = spec["model_id"]
target_dir = data_dir / config
target_dir.mkdir(parents=True, exist_ok=True)
parquet_path = target_dir / "train-00000-of-00001.parquet"
audit = {
label: {"matches": 0, "file_names": set(), "example_files": []}
for label in SCAN_PATTERNS
}
output_sequences: collections.Counter[tuple[str, ...]] = collections.Counter()
seed_counts: collections.Counter[int] = collections.Counter()
profile_counts: collections.Counter[int] = collections.Counter()
trait_value_counts = {trait: collections.Counter() for trait in TRAITS}
profile_mapping: dict[int, tuple[int, ...]] = {}
seen_ids: set[tuple[int, int]] = set()
seen_payload_hashes: dict[str, str] = {}
duplicate_payloads = 0
content_chars = 0
empty_content_blocks = 0
records_with_empty_content = 0
empty_content_example_files: list[str] = []
writer = pq.ParquetWriter(
parquet_path,
ARROW_SCHEMA,
compression="zstd",
compression_level=9,
use_dictionary=True,
write_statistics=True,
)
try:
for member_batch in batched(members, args.batch_size):
rows: list[dict[str, Any]] = []
for info in member_batch:
filename = Path(info.filename).name
match = FILE_RE.match(filename)
assert match is not None
profile_id = int(match.group("profile"))
seed = int(match.group("seed"))
record_key = (profile_id, seed)
if record_key in seen_ids:
raise ValueError(f"duplicate profile/seed in {source_dir}: {record_key}")
seen_ids.add(record_key)
try:
payload = json.loads(zf.read(info).decode("utf-8"))
except Exception as exc:
raise ValueError(f"invalid UTF-8 JSON: {info.filename}: {exc}") from exc
big5, outputs = validate_payload(payload, info.filename)
trait_tuple = tuple(big5[trait] for trait in TRAITS)
previous = profile_mapping.setdefault(profile_id, trait_tuple)
if previous != trait_tuple:
raise ValueError(f"profile {profile_id} maps to multiple Big Five vectors")
payload_hash = normalized_digest(payload)
if payload_hash in seen_payload_hashes:
duplicate_payloads += 1
else:
seen_payload_hashes[payload_hash] = filename
output_sequences[tuple(item["name"] for item in outputs)] += 1
seed_counts[seed] += 1
profile_counts[profile_id] += 1
for trait in TRAITS:
trait_value_counts[trait][big5[trait]] += 1
for item in outputs:
content_chars += len(item["content"])
scan_text(item["content"], filename, audit)
empty_in_record = sum(not item["content"].strip() for item in outputs)
if empty_in_record:
empty_content_blocks += empty_in_record
records_with_empty_content += 1
if len(empty_content_example_files) < 20:
empty_content_example_files.append(filename)
rows.append(
{
"id": f"{config}-{profile_id:04d}-{seed:02d}",
"profile_id": profile_id,
"seed": seed,
"generator_model": model_id,
"openness": big5["Openness"],
"conscientiousness": big5["Conscientiousness"],
"extraversion": big5["Extraversion"],
"agreeableness": big5["Agreeableness"],
"neuroticism": big5["Neuroticism"],
"outputs": outputs,
"source_file": filename,
}
)
write_rows(writer, rows)
finally:
writer.close()
unexpected_seed_values = sorted(set(seed_counts) - {1, 2, 3, 4, 5})
bad_profile_multiplicity = sum(count != 5 for count in profile_counts.values())
unique_vectors = set(profile_mapping.values())
model_report = {
"model_id": model_id,
"config_name": config,
"records": len(members),
"profiles": len(profile_counts),
"unique_big5_vectors": len(unique_vectors),
"seeds": {str(key): seed_counts[key] for key in sorted(seed_counts)},
"unexpected_seed_values": unexpected_seed_values,
"profiles_without_exactly_five_seeds": bad_profile_multiplicity,
"output_blocks_per_record": EXPECTED_OUTPUTS,
"output_name_sequences": [
{"count": count, "names": list(names)}
for names, count in output_sequences.most_common()
],
"duplicate_normalized_payloads": duplicate_payloads,
"content_characters": content_chars,
"empty_content_blocks": empty_content_blocks,
"records_with_empty_content": records_with_empty_content,
"empty_content_example_files": empty_content_example_files,
"trait_value_counts": {
trait: {str(value): counts[value] for value in sorted(counts)}
for trait, counts in trait_value_counts.items()
},
"sensitive_pattern_scan": {
label: {
"matches": item["matches"],
"files": len(item["file_names"]),
"example_files": item["example_files"],
}
for label, item in audit.items()
},
"parquet_file": str(parquet_path.relative_to(output)),
"parquet_size_bytes": parquet_path.stat().st_size,
"parquet_sha256": sha256_file(parquet_path),
}
report["models"][config] = model_report
mappings_by_model[config] = profile_mapping
print(
f"{config}: {len(members):,} records, {len(profile_counts):,} profiles, "
f"{parquet_path.stat().st_size / (1024 * 1024):.1f} MiB",
flush=True,
)
unrecognized = sorted(set(info.filename for info in all_json_members) - recognized)
if unrecognized:
raise ValueError(f"unrecognized JSON files in archive: {len(unrecognized)}")
configs = list(mappings_by_model)
base_mapping = mappings_by_model[configs[0]]
mapping_equal = {
config: mappings_by_model[config] == base_mapping for config in configs[1:]
}
report["cross_model_checks"] = {
"total_records": sum(item["records"] for item in report["models"].values()),
"profile_to_big5_mapping_matches_first_config": mapping_equal,
"archive_contains_only_recognized_model_json": True,
}
report_path = report_dir / "validation_report.json"
report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"wrote {report_path}", flush=True)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
raise