NSU-Data-For-Meno / scripts /dataset.py
Sckwoky's picture
Make complete text dataset ready for curation while originals upload
c30d709 verified
Raw History Blame Contribute Delete
5.93 kB
"""Portable standard-library helper shipped as scripts/dataset.py on the Hub."""
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path
import shutil
import tarfile
def rows(root, partition):
for path in sorted((Path(root) / "data" / partition).glob("*.jsonl.gz")):
with gzip.open(path, "rt", encoding="utf-8") as stream:
for line in stream:
yield json.loads(line)
def file_hash(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def validate(root, require_originals=False):
root = Path(root)
manifest = json.loads((root / "manifest.json").read_text())
if require_originals and not manifest.get("original_archive_upload_complete", False):
raise ValueError("Original archive upload has not completed yet")
for row in json.loads((root / "checksums.json").read_text()):
path = root / row["path"]
if path.stat().st_size != row["bytes"] or file_hash(path) != row["sha256"]:
raise ValueError("File fingerprint mismatch: " + row["path"])
originals = {r["original_id"] for r in rows(root, "originals")}
seen, counts = set(), Counter()
for partition in ["documents", "versions", "quarantine"]:
for r in rows(root, partition):
if r["version_id"] in seen:
raise ValueError("Repeated version ID: " + r["version_id"])
seen.add(r["version_id"])
if hashlib.sha256(r["text"].encode()).hexdigest() != r["text_sha256"]:
raise ValueError("Text fingerprint mismatch: " + r["version_id"])
url_hash = hashlib.sha256(r["url"].encode()).hexdigest()
version_hash = hashlib.sha256((r["url"] + "\0" + r["text_sha256"]).encode()).hexdigest()
if r["document_id"] != "doc-" + url_hash or r["source_id"] != "source-" + url_hash or r["version_id"] != "version-" + version_hash:
raise ValueError("Document identity mismatch: " + r["version_id"])
if r["original_available"] and r["original_id"] not in originals:
raise ValueError("Unresolved original: " + r["original_id"])
if r["collection_role"] != "knowledge" or not isinstance(r["fact_checked"], bool):
raise ValueError("Unexpected curation state: " + r["version_id"])
counts[partition] += 1
for partition, expected in manifest["counts"].items():
count = counts[partition] if partition in counts else sum(1 for _ in rows(root, partition))
if count != expected:
raise ValueError(f"Count mismatch for {partition}: {count} != {expected}")
counts[partition] = count
missing = []
for r in manifest["original_archives"]:
path = root / r["path"]
if not path.exists():
missing.append(r["path"])
elif path.stat().st_size != r["bytes"] or file_hash(path) != r["sha256"]:
raise ValueError("Archive fingerprint mismatch: " + r["path"])
if require_originals and missing:
raise ValueError(f"Download original archives first: {len(missing)} missing")
return {"status": "passed", "counts": dict(counts), "original_archives_not_downloaded": len(missing)}
def extract_original(root, original_id, destination):
root = Path(root)
record = next(r for r in rows(root, "originals") if r["original_id"] == original_id)
archive = root / record["archive_path"]
manifest = json.loads((root / "manifest.json").read_text())
expected = next((r for r in manifest["original_archives"] if r["path"] == record["archive_path"]), None)
if expected is None:
raise FileNotFoundError("Original archive is still uploading; refresh manifest.json after upload completes")
if file_hash(archive) != expected["sha256"]:
raise ValueError("Archive checksum mismatch")
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive) as tf:
# Extract only the indexed regular member, never archive paths.
info = tf.getmember(record["member_path"])
if not info.isfile():
raise ValueError("Original is not a regular archive member")
with tf.extractfile(info) as source:
stream = gzip.GzipFile(fileobj=source) if record["storage_encoding"] == "gzip" else source
with destination.open("wb") as target:
shutil.copyfileobj(stream, target)
if file_hash(destination) != original_id:
destination.unlink()
raise ValueError("Original-byte checksum mismatch")
return {"original_id": original_id, "destination": str(destination)}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["validate", "sample", "show", "extract-original"])
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--partition", default="documents")
parser.add_argument("--id")
parser.add_argument("--out", type=Path)
parser.add_argument("--count", type=int, default=3)
parser.add_argument("--require-originals", action="store_true")
args = parser.parse_args()
if args.command == "validate":
print(json.dumps(validate(args.root, args.require_originals), ensure_ascii=False))
elif args.command == "extract-original":
print(json.dumps(extract_original(args.root, args.id, args.out), ensure_ascii=False))
else:
count = 0
for r in rows(args.root, args.partition):
if args.command == "sample" or args.id in [r.get("document_id"), r.get("version_id"), r.get("source_id"), r.get("url")]:
print(json.dumps(r, ensure_ascii=False))
count += 1
if count >= args.count:
break