orchestra-q-job-scripts / scripts /hf /00_probe_dataset.py
WiktorMatuszek's picture
Add Orchestra-Q HF Jobs scripts
fd68fe9 verified
Raw
History Blame Contribute Delete
3.44 kB
# /// script
# dependencies = ["datasets>=3.0,<5", "huggingface-hub>=0.26,<2"]
# ///
"""Inspect a pinned Hub dataset sample and persist a content-free quality report."""
from __future__ import annotations
from collections import Counter
from datetime import UTC, datetime
import hashlib
import json
import os
import re
from typing import Any
from datasets import load_dataset
from huggingface_hub import HfApi
SECRET = re.compile(r"(?:\bsk-[A-Za-z0-9_-]{12,}|\bhf_[A-Za-z0-9]{12,})")
def _shape(value: Any) -> str:
if value is None:
return "null"
if isinstance(value, list):
return "list"
if isinstance(value, dict):
return "object"
return type(value).__name__
def main() -> None:
repo = os.environ["SOURCE_REPO"]
revision = os.environ["SOURCE_REVISION"]
config = os.getenv("SOURCE_CONFIG") or None
split = os.getenv("SOURCE_SPLIT", "train")
sample_rows = int(os.getenv("SAMPLE_ROWS", "1000"))
dataset = load_dataset(repo, config, split=split, revision=revision, streaming=True)
field_presence: Counter[str] = Counter()
field_shapes: dict[str, Counter[str]] = {}
text_lengths: dict[str, list[int]] = {}
suspected_secrets = 0
duplicate_fingerprints = 0
seen: set[str] = set()
count = 0
for row in dataset.take(sample_rows):
count += 1
canonical = json.dumps(row, sort_keys=True, ensure_ascii=False, default=str)
fingerprint = hashlib.sha256(canonical.encode()).hexdigest()
duplicate_fingerprints += fingerprint in seen
seen.add(fingerprint)
suspected_secrets += bool(SECRET.search(canonical))
for key, value in row.items():
field_presence[key] += value is not None
field_shapes.setdefault(key, Counter())[_shape(value)] += 1
if isinstance(value, str):
text_lengths.setdefault(key, []).append(len(value))
report = {
"schema_version": "1.0.0",
"created_at": datetime.now(UTC).isoformat(),
"source": {"repo_id": repo, "revision": revision, "config": config, "split": split},
"sample_count": count,
"fields": {
key: {
"present": field_presence[key],
"shapes": dict(sorted(field_shapes[key].items())),
"text_length": (
{
"min": min(text_lengths[key]),
"max": max(text_lengths[key]),
"mean": sum(text_lengths[key]) / len(text_lengths[key]),
}
if key in text_lengths
else None
),
}
for key in sorted(field_presence)
},
"findings": {
"suspected_secret_rows": suspected_secrets,
"duplicate_sample_rows": duplicate_fingerprints,
},
}
payload = json.dumps(report, sort_keys=True, indent=2) + "\n"
print(payload)
target = os.getenv("REPORT_REPO")
if target:
HfApi().create_repo(target, repo_type="dataset", private=True, exist_ok=True)
HfApi().upload_file(
path_or_fileobj=payload.encode(),
path_in_repo=os.getenv("REPORT_PATH", "probes/latest.json"),
repo_id=target,
repo_type="dataset",
commit_message=f"Add dataset probe for {repo}@{revision[:12]}",
)
if __name__ == "__main__":
main()