File size: 3,444 Bytes
fd68fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// 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()